Ryanus commited on
Commit
d9c311a
·
verified ·
1 Parent(s): 0663f9d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +405 -233
app.py CHANGED
@@ -6,51 +6,133 @@ import subprocess
6
  import shutil
7
  import zipfile
8
  from datetime import datetime
9
- import traceback
10
 
11
- def run_ffmpeg_with_debug(command, operation_name):
12
- """运行FFmpeg命令并提供详细调试信息"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  try:
14
- print(f"🔧 执行 {operation_name}...")
15
- print(f"📝 命令: {' '.join(command)}")
16
-
17
- result = subprocess.run(
18
- command,
19
- stdout=subprocess.PIPE,
20
- stderr=subprocess.PIPE,
21
- text=True,
22
- timeout=60 # 60秒超时
23
- )
24
 
25
- if result.returncode != 0:
26
- print(f"❌ {operation_name} 失败")
27
- print(f"错误输出: {result.stderr}")
28
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  else:
30
- print(f"✅ {operation_name} 成功")
31
- return True
32
-
33
- except subprocess.TimeoutExpired:
34
- print(f"⏰ {operation_name} 超时")
35
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  except Exception as e:
37
- print(f"💥 {operation_name} 异常: {str(e)}")
38
- return False
39
 
40
- def ffmpeg_cut_video_safe(input_path, start_time, duration, output_path):
41
- """安全的视频切割,使用兼容性最好的参数"""
42
- if not os.path.exists(input_path):
43
- print(f"❌ 输入文件不存在: {input_path}")
44
- return False
45
-
 
 
 
 
 
 
 
 
 
 
 
46
  command = [
47
  'ffmpeg',
48
  '-i', input_path,
49
  '-ss', str(start_time),
50
  '-t', str(duration),
51
  '-c:v', 'libx264',
52
- '-preset', 'medium', # 平衡速度和质量
53
- '-crf', '23', # 适中的质量
54
  '-c:a', 'aac',
55
  '-b:a', '128k',
56
  '-avoid_negative_ts', 'make_zero',
@@ -58,23 +140,11 @@ def ffmpeg_cut_video_safe(input_path, start_time, duration, output_path):
58
  output_path
59
  ]
60
 
61
- success = run_ffmpeg_with_debug(command, f"切割视频 ({os.path.basename(input_path)})")
62
-
63
- if success and os.path.exists(output_path):
64
- file_size = os.path.getsize(output_path) / (1024 * 1024)
65
- print(f"📁 生成文件: {os.path.basename(output_path)} ({file_size:.1f}MB)")
66
- return True
67
- else:
68
- print(f"❌ 切割后文件不存在: {output_path}")
69
- return False
70
 
71
- def ffmpeg_resize_video_safe(input_path, output_path, target_ratio):
72
- """安全的视频比例调整"""
73
- if not os.path.exists(input_path):
74
- print(f"❌ 输入文件不存在: {input_path}")
75
- return False
76
-
77
- # 简化的比例调整,使用pad而不是crop
78
  if target_ratio == '9:16':
79
  filter_complex = "scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2:black"
80
  else:
@@ -87,54 +157,30 @@ def ffmpeg_resize_video_safe(input_path, output_path, target_ratio):
87
  '-c:v', 'libx264',
88
  '-preset', 'medium',
89
  '-crf', '23',
90
- '-c:a', 'copy', # 音频直接复制
91
  '-y',
92
  output_path
93
  ]
94
 
95
- success = run_ffmpeg_with_debug(command, f"调整比例 ({target_ratio})")
96
-
97
- if success and os.path.exists(output_path):
98
- file_size = os.path.getsize(output_path) / (1024 * 1024)
99
- print(f"📁 调整后文件: {os.path.basename(output_path)} ({file_size:.1f}MB)")
100
- return True
101
- else:
102
- print(f"❌ 比例调整后文件不存在: {output_path}")
103
- return False
104
 
105
- def concat_videos_safe(file_list, output_path):
106
- """安全的视频合并"""
107
  if not file_list:
108
- print("❌ 没有文件需要合并")
109
  return False
110
 
111
- # 检查所有输入文件是否存在
112
- valid_files = []
113
- for f in file_list:
114
- if os.path.exists(f):
115
- valid_files.append(f)
116
- print(f"✅ 文件存在: {os.path.basename(f)}")
117
- else:
118
- print(f"❌ 文件不存在: {f}")
119
-
120
  if not valid_files:
121
- print("❌ 没有有效的输入文件")
122
  return False
123
 
124
- # 创建文件列表
125
  list_file = tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt', encoding='utf-8')
126
  try:
127
  for f in valid_files:
128
- # 使用绝对路径,避免路径问题
129
  abs_path = os.path.abspath(f)
130
  list_file.write(f"file '{abs_path}'\n")
131
  list_file.close()
132
 
133
- print(f"📝 文件列表: {list_file.name}")
134
- with open(list_file.name, 'r', encoding='utf-8') as lf:
135
- print("📋 合并列表内容:")
136
- print(lf.read())
137
-
138
  command = [
139
  'ffmpeg',
140
  '-f', 'concat',
@@ -145,46 +191,29 @@ def concat_videos_safe(file_list, output_path):
145
  output_path
146
  ]
147
 
148
- success = run_ffmpeg_with_debug(command, "合并视频")
 
149
 
150
- if success and os.path.exists(output_path):
151
- file_size = os.path.getsize(output_path) / (1024 * 1024)
152
- print(f"📁 合并后文件: {os.path.basename(output_path)} ({file_size:.1f}MB)")
153
- return True
154
- else:
155
- print(f"❌ 合并后文件不存在: {output_path}")
156
- return False
157
-
158
- except Exception as e:
159
- print(f"💥 合并过程异常: {str(e)}")
160
- return False
161
  finally:
162
  try:
163
  os.unlink(list_file.name)
164
  except:
165
  pass
166
 
167
- def process_videos_with_debug(video_files, clip_duration, num_output_videos, target_ratio):
168
- """带调试信息的视频处理"""
169
  if not video_files:
170
- return "❌ 请上传视频文件", None, "没有上传文件"
171
-
172
- print("🚀 开始处理视频...")
173
- print(f"📊 参数: 切片{clip_duration}秒, 生成{num_output_videos}个, 比例{target_ratio}")
174
 
175
  temp_dir = tempfile.mkdtemp()
176
- print(f"📁 临时目录: {temp_dir}")
177
 
178
  try:
179
  all_clips = []
180
 
181
- # 第一步:切割视频
182
- print("📹 第一步:切割视频")
183
  for idx, video_file in enumerate(video_files):
184
  video_path = video_file.name
185
- print(f"🎬 处理视频 {idx+1}: {os.path.basename(video_path)}")
186
 
187
- # 获取视频时长
188
  try:
189
  cmd = [
190
  'ffprobe', '-v', 'quiet',
@@ -194,210 +223,353 @@ def process_videos_with_debug(video_files, clip_duration, num_output_videos, tar
194
  ]
195
  result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
196
  total_duration = float(result.stdout.strip())
197
- print(f"⏱️ 视频时长: {total_duration:.1f}秒")
198
- except Exception as e:
199
- print(f"❌ 无法获取视频时长: {e}")
200
  continue
201
 
202
- # 切割视频片段
203
  start = 0.0
204
  count = 0
205
  while start < total_duration:
206
  duration = min(clip_duration, total_duration - start)
207
  clip_path = os.path.join(temp_dir, f"clip_{idx}_{count}.mp4")
208
 
209
- success = ffmpeg_cut_video_safe(video_path, start, duration, clip_path)
210
- if success:
211
  all_clips.append(clip_path)
212
- else:
213
- print(f"⚠️ 跳过失败的片段: {count}")
214
 
215
  start += clip_duration
216
  count += 1
217
 
218
- print(f"📊 总共切割了 {len(all_clips)} 个片段")
219
-
220
  if not all_clips:
221
- return "❌ 没有成功切割任何片段", None, "切割阶段失败"
222
 
223
- # 第二步:生成混剪视频
224
- print("🎭 第二步:生成混剪视频")
225
  random.shuffle(all_clips)
226
-
227
- output_files = []
228
  clips_per_video = max(1, len(all_clips) // num_output_videos)
 
 
229
 
 
230
  for i in range(num_output_videos):
231
- print(f"🎬 生成第 {i+1} 个混剪视频")
232
-
233
  start_idx = i * clips_per_video
234
  end_idx = len(all_clips) if i == num_output_videos - 1 else (start_idx + clips_per_video)
235
  selected_clips = all_clips[start_idx:end_idx]
236
 
237
  if not selected_clips:
238
- print(f"⚠️ 第 {i+1} 个视频没有片段,跳过")
239
  continue
240
 
241
- print(f"📝 第 {i+1} 个视频使用 {len(selected_clips)} 个片段")
242
-
243
- # 先合并片段
244
  temp_merged = os.path.join(temp_dir, f"merged_{i+1}.mp4")
245
- merge_success = concat_videos_safe(selected_clips, temp_merged)
246
-
247
- if not merge_success:
248
- print(f"❌ 第 {i+1} 个视频合并失败")
249
  continue
250
 
251
- # 再调整比例
252
  timestamp = datetime.now().strftime('%H%M%S')
253
  final_output = os.path.join(temp_dir, f"混剪视频_{target_ratio.replace(':', 'x')}_{i+1}_{timestamp}.mp4")
254
- resize_success = ffmpeg_resize_video_safe(temp_merged, final_output, target_ratio)
255
 
256
- if resize_success:
257
  output_files.append(final_output)
258
- print(f"✅ 第 {i+1} 个混剪视频完成")
259
- else:
260
- print(f"❌ {i+1} 个视频比例调整失败")
 
 
261
 
262
  if not output_files:
263
- error_info = f"生成阶段失败。切割了{len(all_clips)}个片段,但无法生成最终视频。"
264
- return "❌ 未能生成任何混剪视频", None, error_info
265
 
266
- # 第三步:打包
267
- print("📦 第三步:打包文件")
268
  package_dir = tempfile.mkdtemp()
269
  timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
270
  zip_path = os.path.join(package_dir, f"混剪视频包_{target_ratio.replace(':', 'x')}_{timestamp}.zip")
271
 
272
- try:
273
- with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
274
- for video_file in output_files:
275
- arcname = os.path.basename(video_file)
276
- zipf.write(video_file, arcname)
277
- print(f"📦 打包文件: {arcname}")
278
-
279
- # 添加说明
280
- readme = f"""调试版混剪视频包
281
 
282
- 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
283
- 成功生成: {len(output_files)} 个视频
284
- 视频比例: {target_ratio}
285
- 切片时长: {clip_duration}
 
286
 
287
- 文件列表:
288
  """
289
- for i, vf in enumerate(output_files, 1):
290
- size_mb = os.path.getsize(vf) / (1024 * 1024)
291
- readme += f"- 混剪视频_{i}.mp4 ({size_mb:.1f}MB)\n"
292
-
293
- zipf.writestr("README.txt", readme.encode('utf-8'))
294
-
295
- total_size = os.path.getsize(zip_path) / (1024 * 1024)
296
 
297
- success_msg = f"""✅ 处理成功完成!
 
 
 
298
 
299
- 📊 最终统计:
300
- 成功生成: {len(output_files)} 个混剪视频
301
- • 视频比例: {target_ratio}
302
- • 总文件大小: {total_size:.1f}MB
303
- • 切片时长: {clip_duration} 秒
304
 
305
- 💾 点击下方下载按钮获取视频包"""
 
 
306
 
307
- detail_info = f"""详细处理信息:
 
 
 
 
 
 
 
 
 
 
 
308
 
309
- 📹 输入处理:
310
- 输入文件数: {len(video_files)}
311
- 成功切片数: {len(all_clips)}
 
312
 
313
- 🎬 输出统计:
 
314
  """
315
- for i, vf in enumerate(output_files, 1):
316
- size_mb = os.path.getsize(vf) / (1024 * 1024)
317
- detail_info += f"• 混剪视频_{i}: {size_mb:.1f}MB\n"
318
-
319
- print("🎉 所有处理完成!")
320
- return success_msg, zip_path, detail_info
321
-
322
- except Exception as e:
323
- error_msg = f"打包失败: {str(e)}"
324
- print(f"❌ {error_msg}")
325
- return f"❌ {error_msg}", None, str(e)
326
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
  except Exception as e:
328
- error_trace = traceback.format_exc()
329
- print(f"💥 处理过程发生异常:")
330
- print(error_trace)
331
- return f"❌ 处理异常: {str(e)}", None, error_trace
332
 
333
  finally:
334
- # 清理临时文件
335
- try:
336
- shutil.rmtree(temp_dir, ignore_errors=True)
337
- print("🧹 临时文件清理完成")
338
- except:
339
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
 
341
  def main():
342
- with gr.Blocks(title="调试版FFmpeg剪辑工具") as demo:
343
 
344
  gr.HTML("""
345
  <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white; margin-bottom: 20px;">
346
- <h1>🔧 调试版 FFmpeg 自动剪辑工具</h1>
347
- <p style="margin: 10px 0 0 0;">🚀 带详细调试信息,帮助解决处理问题</p>
348
  </div>
349
  """)
350
 
351
- gr.Markdown("""
352
- ### 🔧 调试版特性
353
- - 📝 **详细日志**: 显示每步处理的详细信息
354
- - 🛠️ **错误诊断**: 精确定位问题所在
355
- - 🔍 **文件检查**: 验证每个步骤的文件状态
356
- - ⚡ **稳定处理**: 使用最兼容的FFmpeg参数
357
- """)
358
-
359
- with gr.Row():
360
- with gr.Column():
361
- video_input = gr.File(
362
- label="📤 上传视频文件",
363
- file_types=[".mp4", ".mov", ".avi"],
364
- file_count="multiple"
365
- )
366
-
367
  with gr.Row():
368
- clip_duration = gr.Number(value=3, label="切片时长(秒)", minimum=1, maximum=30)
369
- num_output = gr.Number(value=2, label="生成数量", minimum=1, maximum=5)
370
-
371
- target_ratio = gr.Radio(choices=["9:16", "16:9"], value="9:16", label="视频比例")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
 
373
- process_btn = gr.Button("🔧 开始调试处理", variant="primary")
374
-
375
- with gr.Row():
376
- with gr.Column():
377
- status_output = gr.Textbox(label="处理状态", lines=8, interactive=False)
378
- download_file = gr.File(label="下载结果", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
379
 
380
- with gr.Column():
381
- debug_output = gr.Textbox(label="调试信息", lines=12, interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382
 
 
383
  process_btn.click(
384
- fn=process_videos_with_debug,
385
- inputs=[video_input, clip_duration, num_output, target_ratio],
386
- outputs=[status_output, download_file, debug_output]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  )
388
 
389
  gr.Markdown("""
390
  ---
391
- ### 🔧 调试说明
 
 
 
 
 
 
392
 
393
- 这个调试版本会显示详细的处理过程,帮助识别问题:
 
 
 
 
 
394
 
395
- - ✅ **成功标志**: 显示每步成功完成
396
- - **失败标志**: 显示具体失败原因
397
- - 📁 **文件信息**: 显示文件大小和路径
398
- - 🔧 **命令日志**: 显示执行的FFmpeg命令
 
399
 
400
- 如果仍然失败,请查看"调试信息"栏中的详细错误信息。
 
 
 
401
  """)
402
 
403
  demo.launch()
 
6
  import shutil
7
  import zipfile
8
  from datetime import datetime
9
+ import json
10
 
11
+ # 储存目录设置
12
+ STORAGE_DIR = os.path.expanduser("~/video_storage")
13
+ STORAGE_CONFIG = os.path.join(STORAGE_DIR, "storage_config.json")
14
+
15
+ def init_storage():
16
+ """初始化储存空间"""
17
+ os.makedirs(STORAGE_DIR, exist_ok=True)
18
+
19
+ if not os.path.exists(STORAGE_CONFIG):
20
+ config = {
21
+ "created_time": datetime.now().isoformat(),
22
+ "total_videos": 0,
23
+ "total_size_mb": 0
24
+ }
25
+ with open(STORAGE_CONFIG, 'w', encoding='utf-8') as f:
26
+ json.dump(config, f, ensure_ascii=False, indent=2)
27
+
28
+ def save_to_storage(file_path, metadata=None):
29
+ """保存文件到储存空间"""
30
  try:
31
+ base_name = os.path.basename(file_path)
32
+ target_path = os.path.join(STORAGE_DIR, base_name)
 
 
 
 
 
 
 
 
33
 
34
+ # 避免重名覆盖
35
+ count = 1
36
+ name, ext = os.path.splitext(base_name)
37
+ while os.path.exists(target_path):
38
+ target_path = os.path.join(STORAGE_DIR, f"{name}_{count}{ext}")
39
+ count += 1
40
+
41
+ shutil.copy2(file_path, target_path)
42
+
43
+ # 更新配置
44
+ update_storage_config()
45
+
46
+ return target_path
47
+ except Exception as e:
48
+ print(f"❌ 储存文件失败: {e}")
49
+ return None
50
+
51
+ def update_storage_config():
52
+ """更新储存配置信息"""
53
+ try:
54
+ video_files = [f for f in os.listdir(STORAGE_DIR) if f.lower().endswith(('.mp4', '.mov', '.avi', '.mkv'))]
55
+ total_size = sum(os.path.getsize(os.path.join(STORAGE_DIR, f)) for f in video_files) / (1024 * 1024)
56
+
57
+ config = {
58
+ "updated_time": datetime.now().isoformat(),
59
+ "total_videos": len(video_files),
60
+ "total_size_mb": round(total_size, 1)
61
+ }
62
+
63
+ with open(STORAGE_CONFIG, 'w', encoding='utf-8') as f:
64
+ json.dump(config, f, ensure_ascii=False, indent=2)
65
+ except:
66
+ pass
67
+
68
+ def get_storage_info():
69
+ """获取储存空间信息"""
70
+ try:
71
+ if os.path.exists(STORAGE_CONFIG):
72
+ with open(STORAGE_CONFIG, 'r', encoding='utf-8') as f:
73
+ config = json.load(f)
74
  else:
75
+ config = {"total_videos": 0, "total_size_mb": 0}
76
+
77
+ # 获取视频文件列表
78
+ video_files = []
79
+ if os.path.exists(STORAGE_DIR):
80
+ for f in os.listdir(STORAGE_DIR):
81
+ if f.lower().endswith(('.mp4', '.mov', '.avi', '.mkv')):
82
+ file_path = os.path.join(STORAGE_DIR, f)
83
+ size_mb = os.path.getsize(file_path) / (1024 * 1024)
84
+ mod_time = datetime.fromtimestamp(os.path.getmtime(file_path))
85
+ video_files.append({
86
+ "name": f,
87
+ "size_mb": round(size_mb, 1),
88
+ "modified": mod_time.strftime('%Y-%m-%d %H:%M')
89
+ })
90
+
91
+ # 按修改时间排序
92
+ video_files.sort(key=lambda x: x["modified"], reverse=True)
93
+
94
+ return config, video_files
95
+ except:
96
+ return {"total_videos": 0, "total_size_mb": 0}, []
97
+
98
+ def delete_storage_file(filename):
99
+ """从储存空间删除文件"""
100
+ try:
101
+ file_path = os.path.join(STORAGE_DIR, filename)
102
+ if os.path.exists(file_path):
103
+ os.remove(file_path)
104
+ update_storage_config()
105
+ return f"✅ 已删除文件: {filename}"
106
+ else:
107
+ return f"❌ 文件不存在: {filename}"
108
  except Exception as e:
109
+ return f" 删除失败: {str(e)}"
 
110
 
111
+ def clear_storage():
112
+ """清空储存空间"""
113
+ try:
114
+ count = 0
115
+ if os.path.exists(STORAGE_DIR):
116
+ for f in os.listdir(STORAGE_DIR):
117
+ if f.lower().endswith(('.mp4', '.mov', '.avi', '.mkv')):
118
+ os.remove(os.path.join(STORAGE_DIR, f))
119
+ count += 1
120
+
121
+ update_storage_config()
122
+ return f"✅ 已清空储存空间,删除了 {count} 个文件"
123
+ except Exception as e:
124
+ return f"❌ 清空失败: {str(e)}"
125
+
126
+ def ffmpeg_cut_video(input_path, start_time, duration, output_path):
127
+ """稳定的视频切割"""
128
  command = [
129
  'ffmpeg',
130
  '-i', input_path,
131
  '-ss', str(start_time),
132
  '-t', str(duration),
133
  '-c:v', 'libx264',
134
+ '-preset', 'medium',
135
+ '-crf', '23',
136
  '-c:a', 'aac',
137
  '-b:a', '128k',
138
  '-avoid_negative_ts', 'make_zero',
 
140
  output_path
141
  ]
142
 
143
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
144
+ return result.returncode == 0 and os.path.exists(output_path)
 
 
 
 
 
 
 
145
 
146
+ def ffmpeg_resize_video(input_path, output_path, target_ratio):
147
+ """稳定的比例调整"""
 
 
 
 
 
148
  if target_ratio == '9:16':
149
  filter_complex = "scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2:black"
150
  else:
 
157
  '-c:v', 'libx264',
158
  '-preset', 'medium',
159
  '-crf', '23',
160
+ '-c:a', 'copy',
161
  '-y',
162
  output_path
163
  ]
164
 
165
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
166
+ return result.returncode == 0 and os.path.exists(output_path)
 
 
 
 
 
 
 
167
 
168
+ def concat_videos(file_list, output_path):
169
+ """稳定的视频合并"""
170
  if not file_list:
 
171
  return False
172
 
173
+ valid_files = [f for f in file_list if os.path.exists(f)]
 
 
 
 
 
 
 
 
174
  if not valid_files:
 
175
  return False
176
 
 
177
  list_file = tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt', encoding='utf-8')
178
  try:
179
  for f in valid_files:
 
180
  abs_path = os.path.abspath(f)
181
  list_file.write(f"file '{abs_path}'\n")
182
  list_file.close()
183
 
 
 
 
 
 
184
  command = [
185
  'ffmpeg',
186
  '-f', 'concat',
 
191
  output_path
192
  ]
193
 
194
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
195
+ return result.returncode == 0 and os.path.exists(output_path)
196
 
 
 
 
 
 
 
 
 
 
 
 
197
  finally:
198
  try:
199
  os.unlink(list_file.name)
200
  except:
201
  pass
202
 
203
+ def process_videos_with_storage(video_files, clip_duration, num_output_videos, target_ratio):
204
+ """带储存功能的视频处理"""
205
  if not video_files:
206
+ return "❌ 请上传视频文件", None, "", ""
 
 
 
207
 
208
  temp_dir = tempfile.mkdtemp()
 
209
 
210
  try:
211
  all_clips = []
212
 
213
+ # 切割所有视频
 
214
  for idx, video_file in enumerate(video_files):
215
  video_path = video_file.name
 
216
 
 
217
  try:
218
  cmd = [
219
  'ffprobe', '-v', 'quiet',
 
223
  ]
224
  result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
225
  total_duration = float(result.stdout.strip())
226
+ except:
 
 
227
  continue
228
 
 
229
  start = 0.0
230
  count = 0
231
  while start < total_duration:
232
  duration = min(clip_duration, total_duration - start)
233
  clip_path = os.path.join(temp_dir, f"clip_{idx}_{count}.mp4")
234
 
235
+ if ffmpeg_cut_video(video_path, start, duration, clip_path):
 
236
  all_clips.append(clip_path)
 
 
237
 
238
  start += clip_duration
239
  count += 1
240
 
 
 
241
  if not all_clips:
242
+ return "❌ 切割失败,请检查视频文件", None, "", ""
243
 
244
+ # 随机打乱并分组
 
245
  random.shuffle(all_clips)
 
 
246
  clips_per_video = max(1, len(all_clips) // num_output_videos)
247
+ output_files = []
248
+ stored_files = []
249
 
250
+ # 生成混剪视频
251
  for i in range(num_output_videos):
 
 
252
  start_idx = i * clips_per_video
253
  end_idx = len(all_clips) if i == num_output_videos - 1 else (start_idx + clips_per_video)
254
  selected_clips = all_clips[start_idx:end_idx]
255
 
256
  if not selected_clips:
 
257
  continue
258
 
259
+ # 合并片段
 
 
260
  temp_merged = os.path.join(temp_dir, f"merged_{i+1}.mp4")
261
+ if not concat_videos(selected_clips, temp_merged):
 
 
 
262
  continue
263
 
264
+ # 调整比例
265
  timestamp = datetime.now().strftime('%H%M%S')
266
  final_output = os.path.join(temp_dir, f"混剪视频_{target_ratio.replace(':', 'x')}_{i+1}_{timestamp}.mp4")
 
267
 
268
+ if ffmpeg_resize_video(temp_merged, final_output, target_ratio):
269
  output_files.append(final_output)
270
+
271
+ # 🔥 自动保存到储存空间
272
+ stored_path = save_to_storage(final_output)
273
+ if stored_path:
274
+ stored_files.append(os.path.basename(stored_path))
275
 
276
  if not output_files:
277
+ return "❌ 生成混剪视频失败", None, "", ""
 
278
 
279
+ # 打包下载文件
 
280
  package_dir = tempfile.mkdtemp()
281
  timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
282
  zip_path = os.path.join(package_dir, f"混剪视频包_{target_ratio.replace(':', 'x')}_{timestamp}.zip")
283
 
284
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
285
+ for video_file in output_files:
286
+ arcname = os.path.basename(video_file)
287
+ zipf.write(video_file, arcname)
288
+
289
+ readme = f"""# 混剪视频包
 
 
 
290
 
291
+ ## 📊 生成信息
292
+ - 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
293
+ - 视频数量: {len(output_files)}
294
+ - 视频比例: {target_ratio}
295
+ - 切片时长: {clip_duration} 秒
296
 
297
+ ## 📁 文件列表
298
  """
299
+ for i, vf in enumerate(output_files, 1):
300
+ size_mb = os.path.getsize(vf) / (1024 * 1024)
301
+ readme += f"- 混剪视频_{i}.mp4 ({size_mb:.1f}MB)\n"
 
 
 
 
302
 
303
+ readme += f"""
304
+ ## 💾 储存信息
305
+ 所有视频已自动保存到本地储存空间:
306
+ {', '.join(stored_files)}
307
 
308
+ ## 📱 使用说明
309
+ 视频已按 {target_ratio} 比例优化,可直接发布到相应平台。
 
 
 
310
 
311
+ ---
312
+ FFmpeg 自动混剪工具制作
313
+ """
314
 
315
+ zipf.writestr("README.txt", readme.encode('utf-8'))
316
+
317
+ total_size = os.path.getsize(zip_path) / (1024 * 1024)
318
+ platform_info = "📱 短视频平台" if target_ratio == '9:16' else "🖥️ 长视频平台"
319
+
320
+ success_msg = f"""✅ 混剪完成并已储存!
321
+
322
+ 📊 **生成统计:**
323
+ • 🎬 混剪视频: {len(output_files)} 个
324
+ • 📐 视频比例: {target_ratio}
325
+ • 🎯 适合平台: {platform_info}
326
+ • 📦 下载包大小: {total_size:.1f}MB
327
 
328
+ 💾 **自动储存:**
329
+ 📁 储存位置: ~/video_storage/
330
+ 🔥 已保存文件: {len(stored_files)}
331
+ • ✅ 永久保存,不会丢失
332
 
333
+ ⬇️ **立即下载:**
334
+ 点击下方按钮下载打包文件
335
  """
336
+
337
+ details = f"""🎬 **视频详情:**
338
+
339
+ """
340
+ for i, vf in enumerate(output_files, 1):
341
+ size_mb = os.path.getsize(vf) / (1024 * 1024)
342
+ details += f"• 混剪视频_{i}: {size_mb:.1f}MB\n"
343
+
344
+ details += f"""
345
+ 💾 **储存详情:**
346
+ """
347
+ for i, stored_file in enumerate(stored_files, 1):
348
+ details += f"• 已储存: {stored_file}\n"
349
+
350
+ # 获取最新储存信息
351
+ config, video_list = get_storage_info()
352
+ storage_info = f"""📊 **储存空间状态:**
353
+
354
+ 💾 总计: {config['total_videos']} 个视频
355
+ 📦 总大小: {config['total_size_mb']}MB
356
+ 📁 位置: ~/video_storage/
357
+
358
+ 📋 **最新文件:**
359
+ """
360
+
361
+ for video in video_list[:5]: # 只显示最新5个
362
+ storage_info += f"• {video['name']} ({video['size_mb']}MB) - {video['modified']}\n"
363
+
364
+ return success_msg, zip_path, details, storage_info
365
+
366
  except Exception as e:
367
+ return f"❌ 处理失败: {str(e)}", None, "", ""
 
 
 
368
 
369
  finally:
370
+ shutil.rmtree(temp_dir, ignore_errors=True)
371
+
372
+ def refresh_storage_display():
373
+ """刷新储存空间显示"""
374
+ config, video_list = get_storage_info()
375
+
376
+ storage_display = f"""💾 **储存空间概览**
377
+
378
+ 📊 **统计信息:**
379
+ • 总视频数量: {config['total_videos']} 个
380
+ • 总占用空间: {config['total_size_mb']}MB
381
+ • 储存位置: ~/video_storage/
382
+
383
+ 📁 **文件列表:**
384
+ """
385
+
386
+ if video_list:
387
+ for video in video_list:
388
+ storage_display += f"• {video['name']} ({video['size_mb']}MB) - {video['modified']}\n"
389
+ else:
390
+ storage_display += "暂无文件\n"
391
+
392
+ # 生成文件选择列表
393
+ file_choices = [video['name'] for video in video_list]
394
+
395
+ return storage_display, gr.Dropdown(choices=file_choices, label="选择要删除的文件", interactive=True)
396
+
397
+ def handle_delete_file(filename):
398
+ """处理文件删除"""
399
+ if not filename:
400
+ return "⚠️ 请选择要删除的文件", refresh_storage_display()[0], refresh_storage_display()[1]
401
+
402
+ result = delete_storage_file(filename)
403
+ new_display, new_dropdown = refresh_storage_display()
404
+ return result, new_display, new_dropdown
405
+
406
+ def handle_clear_storage():
407
+ """处理清空储存"""
408
+ result = clear_storage()
409
+ new_display, new_dropdown = refresh_storage_display()
410
+ return result, new_display, new_dropdown
411
+
412
+ # 初始化储存空间
413
+ init_storage()
414
 
415
  def main():
416
+ with gr.Blocks(title="FFmpeg混剪+储存管理", theme=gr.themes.Soft()) as demo:
417
 
418
  gr.HTML("""
419
  <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white; margin-bottom: 20px;">
420
+ <h1>🎬 FFmpeg 混剪工具 + 储存管理</h1>
421
+ <p style="margin: 10px 0 0 0;">长视频切片 → 智能混剪 → 比例调整 → 自动储存 → 永久保存</p>
422
  </div>
423
  """)
424
 
425
+ with gr.Tabs():
426
+ # 第一个标签页:视频处理
427
+ with gr.TabItem("🎬 视频混剪"):
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  with gr.Row():
429
+ with gr.Column(scale=2):
430
+ video_input = gr.File(
431
+ label="📤 上传视频文件 (支持多个)",
432
+ file_types=[".mp4", ".mov", ".avi", ".mkv"],
433
+ file_count="multiple",
434
+ height=120
435
+ )
436
+
437
+ with gr.Row():
438
+ clip_duration = gr.Number(
439
+ value=3,
440
+ label="切片时长(秒)",
441
+ minimum=1,
442
+ maximum=3600
443
+ )
444
+ num_output = gr.Number(
445
+ value=3,
446
+ label="生成数量",
447
+ minimum=1,
448
+ maximum=100
449
+ )
450
+
451
+ ratio_selection = gr.Radio(
452
+ choices=["9:16", "16:9"],
453
+ value="9:16",
454
+ label="📐 视频比例",
455
+ info="9:16适合抖音快手 | 16:9适合YouTube B站"
456
+ )
457
+
458
+ process_btn = gr.Button("🎬 开始混剪并储存", variant="primary", size="lg")
459
+
460
+ with gr.Column(scale=1):
461
+ status_output = gr.Textbox(
462
+ label="📊 处理状态",
463
+ lines=12,
464
+ interactive=False
465
+ )
466
 
467
+ with gr.Row():
468
+ with gr.Column():
469
+ download_file = gr.File(label="📦 下载混剪视频包", interactive=False)
470
+
471
+ with gr.Column():
472
+ details_output = gr.Textbox(
473
+ label="📝 处理详情",
474
+ lines=12,
475
+ interactive=False
476
+ )
477
+
478
+ with gr.Column():
479
+ storage_status = gr.Textbox(
480
+ label="💾 储存状态",
481
+ lines=12,
482
+ interactive=False
483
+ )
484
 
485
+ # 第二个标签页:储存管理
486
+ with gr.TabItem("💾 储存管理"):
487
+ with gr.Row():
488
+ with gr.Column(scale=2):
489
+ storage_display = gr.Textbox(
490
+ label="📁 储存空间",
491
+ lines=15,
492
+ interactive=False,
493
+ value="点击刷新按钮查看储存状态"
494
+ )
495
+
496
+ with gr.Column(scale=1):
497
+ refresh_btn = gr.Button("🔄 刷新储存状态", variant="secondary")
498
+
499
+ gr.Markdown("### 🗑️ 文件管理")
500
+
501
+ file_selector = gr.Dropdown(
502
+ choices=[],
503
+ label="选择文件",
504
+ interactive=True
505
+ )
506
+
507
+ with gr.Row():
508
+ delete_btn = gr.Button("🗑️ 删除文件", variant="secondary")
509
+ clear_btn = gr.Button("🧹 清空储存", variant="stop")
510
+
511
+ operation_result = gr.Textbox(
512
+ label="操作结果",
513
+ lines=3,
514
+ interactive=False
515
+ )
516
 
517
+ # 事件绑定
518
  process_btn.click(
519
+ fn=process_videos_with_storage,
520
+ inputs=[video_input, clip_duration, num_output, ratio_selection],
521
+ outputs=[status_output, download_file, details_output, storage_status]
522
+ )
523
+
524
+ refresh_btn.click(
525
+ fn=refresh_storage_display,
526
+ outputs=[storage_display, file_selector]
527
+ )
528
+
529
+ delete_btn.click(
530
+ fn=handle_delete_file,
531
+ inputs=[file_selector],
532
+ outputs=[operation_result, storage_display, file_selector]
533
+ )
534
+
535
+ clear_btn.click(
536
+ fn=handle_clear_storage,
537
+ outputs=[operation_result, storage_display, file_selector]
538
+ )
539
+
540
+ # 页面加载时自动刷新储存显示
541
+ demo.load(
542
+ fn=refresh_storage_display,
543
+ outputs=[storage_display, file_selector]
544
  )
545
 
546
  gr.Markdown("""
547
  ---
548
+ ### 📖 功能说明
549
+
550
+ **🎬 视频混剪功能:**
551
+ - ⚡ 自动切片和随机混剪
552
+ - 📐 支持9:16/16:9比例调整
553
+ - 📦 打包下载所有生成视频
554
+ - 💾 **自动储存到本地目录**
555
 
556
+ **💾 储存管理功能:**
557
+ - 📁 所有生成视频自动保存到 `~/video_storage/`
558
+ - 🔄 实时查看储存空间使用情况
559
+ - 🗑️ 支持单个文件删除
560
+ - 🧹 支持清空全部储存文��
561
+ - 📊 显示文件详细信息(大小、时间)
562
 
563
+ **🔥 储存优势:**
564
+ - **永久保存**: 文件不会因临时目录清理而丢失
565
+ - 🚀 **快速访问**: 本地储存,无需重新下载
566
+ - 📱 **灵活管理**: 随时查看、删除不需要的文件
567
+ - 💾 **空间监控**: 实时显示储存使用情况
568
 
569
+ **⚠️ 注意事项:**
570
+ - 储存目录位于用户主目录下的 `video_storage` 文件夹
571
+ - 请定期清理不需要的文件以节省磁盘空间
572
+ - 删除操作不可恢复,请谨慎操作
573
  """)
574
 
575
  demo.launch()