from flask import Flask, render_template, request, send_file, jsonify import os import tempfile import subprocess from zipfile import ZipFile # Initialize the Flask app, setting the template folder to current directory app = Flask(__name__, template_folder='.') # Ensure FFmpeg is accessible and executable ffmpeg_path = "ffmpeg" # Adjust if ffmpeg is not on PATH @app.route('/') def home(): return render_template('html.html') @app.route('/process', methods=['POST']) def process_video(): try: video_file = request.files['video'] action = request.form['action'] format_option = request.form.get('format') copy_streams = 'copy_streams' in request.form # Save the uploaded video to a temporary file temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') video_file.save(temp_file.name) output_path = tempfile.mktemp(suffix=f".{format_option or 'mp4'}") # Prepare ffmpeg command based on action command = [ffmpeg_path, '-y', '-i', temp_file.name] if action == 'Convert Format' and format_option: command.extend(['-c', 'copy' if copy_streams else 'libx264', output_path]) elif action == 'Trim Video': start_time = request.form.get('start_time') duration = request.form.get('duration') command.extend(['-ss', start_time, '-t', duration, '-c', 'copy' if copy_streams else 'libx264', output_path]) elif action == 'Resize Video': width = request.form.get('width') height = request.form.get('height') command.extend(['-vf', f'scale={width}:{height}', '-c:a', 'copy', output_path]) elif action == 'Extract Audio': output_path = tempfile.mktemp(suffix=".mp3") command.extend(['-vn', '-acodec', 'mp3', output_path]) elif action == 'Extract Frames': frame_output_dir = tempfile.mkdtemp() command.extend(['-vf', 'fps=1', f'{frame_output_dir}/frame_%03d.png']) # Run the ffmpeg command result = subprocess.run(command, capture_output=True, text=True) if result.returncode != 0: return jsonify({"error": f"Processing failed: {result.stderr}"}), 500 # Handle response if action == 'Extract Frames': zip_path = os.path.join(tempfile.gettempdir(), "frames.zip") with ZipFile(zip_path, 'w') as zipf: for frame_file in os.listdir(frame_output_dir): zipf.write(os.path.join(frame_output_dir, frame_file), frame_file) return send_file(zip_path, as_attachment=True, download_name="frames.zip") else: return send_file(output_path, as_attachment=True) finally: os.remove(temp_file.name) if os.path.exists(output_path): os.remove(output_path) # Run the app using waitress (adjust port as needed for Hugging Face Spaces) if __name__ == '__main__': from waitress import serve serve(app, host='0.0.0.0', port=7860)