Spaces:
Sleeping
Sleeping
import shutil | |
import subprocess | |
from fastapi import UploadFile, File, Form | |
from fastapi.responses import FileResponse | |
from fastapi import APIRouter, BackgroundTasks | |
import os | |
from endpoints.utils import get_file_name | |
from endpoints.utils import remove_content_from_dir | |
router = APIRouter() | |
async def cut_videos( | |
video: UploadFile = File(...), | |
start_time: str = Form(...), | |
end_time: str = Form(...), | |
background_tasks: BackgroundTasks = BackgroundTasks() | |
): | |
temp_dir = "./data/video_editor/videos" | |
if not os.path.exists(temp_dir): | |
os.makedirs(temp_dir) | |
output_video_path = save_and_cut(video, temp_dir, start_time, end_time) | |
# send video back | |
video_name = get_file_name("video_cut") | |
# background_tasks.add_task(remove_content_from_dir, temp_dir) | |
return FileResponse(output_video_path, media_type="video/mp4", filename=video_name) | |
def save_and_cut(video: UploadFile, temp_dir, start_time, end_time): | |
# Save uploaded video to temporary directory | |
video_path = os.path.join(temp_dir, video.filename) | |
with open(video_path, 'wb') as buffer: | |
shutil.copyfileobj(video.file, buffer) | |
# Output video path | |
output_video_path = os.path.join(temp_dir, "output.mp4") | |
# Command to cut video using ffmpeg | |
ffmpeg_command = [ | |
"ffmpeg", | |
"-i", video_path, | |
"-ss", start_time, | |
"-to", end_time, | |
"-y", output_video_path | |
] | |
# Execute ffmpeg command | |
subprocess.run(ffmpeg_command, check=True) | |
return output_video_path | |