RandomPersonRR commited on
Commit
2b5095f
·
verified ·
1 Parent(s): 0e05720

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -73
app.py CHANGED
@@ -1,93 +1,75 @@
1
- from flask import Flask, render_template, request, send_file
2
  import os
3
  import tempfile
4
  import subprocess
5
- import zipfile
6
 
7
- # Initialize the Flask app, tell it to look in the current directory for templates
8
  app = Flask(__name__, template_folder='.')
9
 
 
 
 
10
  @app.route('/')
11
  def home():
12
- return render_template('html.html') # Flask will look in the current directory
13
 
14
  @app.route('/process', methods=['POST'])
15
  def process_video():
16
- video_file = request.files['video']
17
- action = request.form['action']
18
- copy_streams = 'copy_streams' in request.form # Check if the user selected "copy streams"
 
 
19
 
20
- # Save the uploaded video to a temporary file
21
- temp_file = tempfile.NamedTemporaryFile(delete=False)
22
- video_file.save(temp_file.name)
23
 
24
- output_path = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4').name # Default output format
 
 
 
25
 
26
- # Process video based on action
27
- if action == 'Convert Format':
28
- selected_format = request.form['format']
29
- output_path = tempfile.NamedTemporaryFile(delete=False, suffix=f'.{selected_format}').name # Adjust output format based on user selection
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- if copy_streams:
32
- # If "copy streams" is selected, try to copy streams without re-encoding
33
- result = subprocess.run(['ffmpeg', '-i', temp_file.name, '-c:v', 'copy', '-c:a', 'copy', '-y', output_path], capture_output=True)
34
- if result.returncode != 0:
35
- # If copying the streams failed, re-encode the video
36
- subprocess.run(['ffmpeg', '-i', temp_file.name, '-y', output_path])
37
- else:
38
- subprocess.run(['ffmpeg', '-i', temp_file.name, '-y', output_path])
39
- elif action == 'Trim Video':
40
- start_time = request.form['start_time']
41
- duration = request.form['duration']
42
- output_path = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4').name # Example output format
43
 
44
- if copy_streams:
45
- # Try to copy streams during trim operation (if selected)
46
- result = subprocess.run(['ffmpeg', '-i', temp_file.name, '-ss', start_time, '-t', duration, '-c:v', 'copy', '-c:a', 'copy', '-y', output_path], capture_output=True)
47
- if result.returncode != 0:
48
- # If copying the streams failed, re-encode the video
49
- subprocess.run(['ffmpeg', '-i', temp_file.name, '-ss', start_time, '-t', duration, '-y', output_path])
50
- else:
51
- subprocess.run(['ffmpeg', '-i', temp_file.name, '-ss', start_time, '-t', duration, '-y', output_path])
52
- elif action == 'Resize Video':
53
- width = request.form['width']
54
- height = request.form['height']
55
- output_path = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4').name # Example output format
56
- subprocess.run(['ffmpeg', '-i', temp_file.name, '-vf', f'scale={width}:{height}', '-y', output_path])
57
- elif action == 'Extract Audio':
58
- output_path = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3').name # Output audio in MP3 format
59
- subprocess.run(['ffmpeg', '-i', temp_file.name, '-vn', '-acodec', 'mp3', '-y', output_path])
60
- elif action == 'Extract Frames':
61
- # Extract frames and save as .jpg files
62
- frame_dir = tempfile.mkdtemp() # Create a temporary directory to store frames
63
- output_zip = tempfile.NamedTemporaryFile(delete=False, suffix='.zip').name # Output ZIP file
64
-
65
- # Extract frames from the video (saving as JPG files)
66
- subprocess.run(['ffmpeg', '-i', temp_file.name, '-an', f'{frame_dir}/frame_%04d.jpg', '-y'])
67
 
68
- # Create a ZIP file containing the frames
69
- with zipfile.ZipFile(output_zip, 'w', zipfile.ZIP_DEFLATED) as zipf:
70
- for frame in os.listdir(frame_dir):
71
- if frame.endswith('.jpg'):
72
- zipf.write(os.path.join(frame_dir, frame), frame) # Write each frame into the ZIP
73
-
74
- # Clean up the extracted frames directory
75
- for frame in os.listdir(frame_dir):
76
- os.remove(os.path.join(frame_dir, frame))
77
- os.rmdir(frame_dir)
78
-
79
- # Send the ZIP file containing the frames
80
- return send_file(output_zip, as_attachment=True, mimetype='application/zip')
81
- elif action == 'Change Video Speed':
82
- speed_factor = request.form['speed_factor']
83
- output_path = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4').name # Example output format
84
- subprocess.run(['ffmpeg', '-i', temp_file.name, '-filter:v', f'setpts={1/speed_factor}*PTS', '-y', output_path])
85
-
86
- # Send the processed file back as a download (if applicable)
87
- if os.path.exists(output_path):
88
- return send_file(output_path, as_attachment=True)
89
 
90
- return 'Error processing video', 500
 
 
 
91
 
 
92
  if __name__ == '__main__':
93
- app.run(debug=True)
 
 
1
+ from flask import Flask, render_template, request, send_file, jsonify
2
  import os
3
  import tempfile
4
  import subprocess
5
+ from zipfile import ZipFile
6
 
7
+ # Initialize the Flask app, setting the template folder to current directory
8
  app = Flask(__name__, template_folder='.')
9
 
10
+ # Ensure FFmpeg is accessible and executable
11
+ ffmpeg_path = "ffmpeg" # Adjust if ffmpeg is not on PATH
12
+
13
  @app.route('/')
14
  def home():
15
+ return render_template('html.html')
16
 
17
  @app.route('/process', methods=['POST'])
18
  def process_video():
19
+ try:
20
+ video_file = request.files['video']
21
+ action = request.form['action']
22
+ format_option = request.form.get('format')
23
+ copy_streams = 'copy_streams' in request.form
24
 
25
+ # Save the uploaded video to a temporary file
26
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
27
+ video_file.save(temp_file.name)
28
 
29
+ output_path = tempfile.mktemp(suffix=f".{format_option or 'mp4'}")
30
+
31
+ # Prepare ffmpeg command based on action
32
+ command = [ffmpeg_path, '-y', '-i', temp_file.name]
33
 
34
+ if action == 'Convert Format' and format_option:
35
+ command.extend(['-c', 'copy' if copy_streams else 'libx264', output_path])
36
+ elif action == 'Trim Video':
37
+ start_time = request.form.get('start_time')
38
+ duration = request.form.get('duration')
39
+ command.extend(['-ss', start_time, '-t', duration, '-c', 'copy' if copy_streams else 'libx264', output_path])
40
+ elif action == 'Resize Video':
41
+ width = request.form.get('width')
42
+ height = request.form.get('height')
43
+ command.extend(['-vf', f'scale={width}:{height}', '-c:a', 'copy', output_path])
44
+ elif action == 'Extract Audio':
45
+ output_path = tempfile.mktemp(suffix=".mp3")
46
+ command.extend(['-vn', '-acodec', 'mp3', output_path])
47
+ elif action == 'Extract Frames':
48
+ frame_output_dir = tempfile.mkdtemp()
49
+ command.extend(['-vf', 'fps=1', f'{frame_output_dir}/frame_%03d.png'])
50
 
51
+ # Run the ffmpeg command
52
+ result = subprocess.run(command, capture_output=True, text=True)
 
 
 
 
 
 
 
 
 
 
53
 
54
+ if result.returncode != 0:
55
+ return jsonify({"error": f"Processing failed: {result.stderr}"}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ # Handle response
58
+ if action == 'Extract Frames':
59
+ zip_path = os.path.join(tempfile.gettempdir(), "frames.zip")
60
+ with ZipFile(zip_path, 'w') as zipf:
61
+ for frame_file in os.listdir(frame_output_dir):
62
+ zipf.write(os.path.join(frame_output_dir, frame_file), frame_file)
63
+ return send_file(zip_path, as_attachment=True, download_name="frames.zip")
64
+ else:
65
+ return send_file(output_path, as_attachment=True)
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
+ finally:
68
+ os.remove(temp_file.name)
69
+ if os.path.exists(output_path):
70
+ os.remove(output_path)
71
 
72
+ # Run the app using waitress (adjust port as needed for Hugging Face Spaces)
73
  if __name__ == '__main__':
74
+ from waitress import serve
75
+ serve(app, host='0.0.0.0', port=7860)