The following code works fine locally, but on render it raises the error:
{“error”:“[Errno 32] Broken pipe\n\nMoviePy error: FFMPEG encountered the following error while writing file ./temp/g8TzTqd6Xfg_output_video.mp4:\n\n b’./temp/g8TzTqd6Xfg_output_video.mp4: No such file or directory\n’”}
The code:
from flask import Flask, request, send_file, jsonify, after_this_request
from pytube import YouTube
import moviepy.editor as mp
import json
import os
import io
app = Flask(__name__)
@app.route('/')
def index():
try:
video_id = request.args.get('id')
yt = YouTube("https://www.youtube.com/watch?v=" + video_id)
video_stream = yt.streams.filter(res="720p").first()
if not video_stream:
return jsonify({"error": "Stream not found."})
start_time = request.args.get('start')
end_time = request.args.get('end')
print("Trimming vídeo...")
video_clip = mp.VideoFileClip(
video_stream.url).subclip(start_time, end_time)
output_video_path = "./temp/" + video_id + "_output_video.mp4"
video_clip.write_videofile(output_video_path)
video_clip.close()
print("Download finished!")
@after_this_request
def remove_temp_files(response):
try:
os.remove(output_video_path)
except Exception as e:
print("Error removing temp files:", e)
return response
with open(output_video_path, 'rb') as video_file:
video_data = video_file.read()
response = send_file(
io.BytesIO(video_data),
as_attachment=True,
mimetype="video/mp4",
download_name= video_id + "output_video.mp4"
)
response.headers["Content-Disposition"] = "attachment; filename=" + video_id + "_output_video.mp4"
return response
except Exception as e:
return jsonify({"error": str(e)})
if __name__ == '__main__':
app.run()