Update main.py
Browse files357 unmodified lines3583593603613623613623633643652 unmodified lines3683693703713723733713723733743753763753763773783793783793803813823833843853813823833843853863873883893903913873883893933943953903913923933943953963973983994004014024034044054064074084092 unmodified lines4124134144044054064074084154164174104184194124134204214224234243 unmodified lines428429430423424431432433434427435436429430431437438439440441442357 unmodified lines print(traceback.format_exc()) raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")
@app.post("/concatenate_videos_with_music")async def concatenate_videos_with_music(request: Request):@app.post("/create_slideshow")async def create_slideshow(request: Request): try: # Generate a unique filename for the output output_filename = f"{uuid.uuid4()}.mp4"2 unmodified lines os.makedirs(temp_dir, exist_ok=True)
data = await request.json() video_urls = data.get("video_urls") music_url = data.get("music_url") volume_adjustment = data.get("volume_adjustment", 1.0) # Default volume if not specified image_urls = data.get("image_urls") audio_url = data.get("audio_url") duration = data.get("duration", 4) # Default to 4 seconds per image if not specified
if not video_urls or not isinstance(video_urls, list): raise HTTPException(status_code=400, detail="Invalid video_urls in request. Must be a list of URLs.") if not image_urls or not isinstance(image_urls, list): raise HTTPException(status_code=400, detail="Invalid image_urls in request. Must be a list of URLs.")
if not music_url: raise HTTPException(status_code=400, detail="Missing music_url in request.") if not audio_url: raise HTTPException(status_code=400, detail="Missing audio_url in request.")
# Download the video files video_files = [] for i, url in enumerate(video_urls): video_file = await download_file(url, f"_{i}.mp4") video_files.append(video_file) # Download the images image_files = [] for i, url in enumerate(image_urls): image_file = await download_file(url, f"_{i}.jpg") image_files.append(image_file)
# Create a temporary file with the list of input files concat_list_path = os.path.join(temp_dir, "concat_list.txt") with open(concat_list_path, "w") as f: for file in video_files: f.write(f"file '{file}'\n") # Download audio file audio_file = await download_file(audio_url, ".mp3")
# First concatenate all videos concat_output = os.path.join(temp_dir, "concat_output.mp4") concat_cmd = f"ffmpeg -f concat -safe 0 -i {concat_list_path} -c:v copy -an {concat_output}" # Create a text file with the list of images and their duration images_list_path = os.path.join(temp_dir, "images_list.txt") with open(images_list_path, "w") as f: for file in image_files: f.write(f"file '{file}'\n") f.write(f"duration {duration}\n") # Add the last image again with a small duration to prevent ffmpeg from cutting it off f.write(f"file '{image_files[-1]}'\n") f.write(f"duration 0.1\n")
# Create intermediate video without audio intermediate_video = os.path.join(temp_dir, "intermediate.mp4") # Use the complex concat demuxer for images to create a slideshow concat_cmd = ( f'ffmpeg -f concat -safe 0 -i {images_list_path} -vsync vfr ' f'-pix_fmt yuv420p -c:v libx264 -r 30 {intermediate_video}' ) process = await asyncio.create_subprocess_shell( concat_cmd, stdout=asyncio.subprocess.PIPE,2 unmodified lines stdout, stderr = await process.communicate()
if process.returncode != 0: print(f"FFmpeg concat error: {stderr.decode()}") raise HTTPException(status_code=500, detail=f"FFmpeg concat failed: {stderr.decode()}")
# Download music file music_file = await download_file(music_url, ".mp3") print(f"FFmpeg slideshow creation error: {stderr.decode()}") raise HTTPException(status_code=500, detail=f"FFmpeg slideshow creation failed: {stderr.decode()}")
# Add music to the concatenated video # Add audio to the slideshow final_cmd = ( f'ffmpeg -i {concat_output} -i {music_file} -map 0:v -map 1:a ' f'-c:v copy -c:a aac -shortest -af "volume={volume_adjustment}" {output_path}' f'ffmpeg -i {intermediate_video} -i {audio_file} -map 0:v -map 1:a ' f'-c:v copy -c:a aac -shortest {output_path}' ) process = await asyncio.create_subprocess_shell( final_cmd,3 unmodified lines stdout, stderr = await process.communicate()
if process.returncode != 0: print(f"FFmpeg music mix error: {stderr.decode()}") raise HTTPException(status_code=500, detail=f"FFmpeg music mixing failed: {stderr.decode()}") print(f"FFmpeg audio addition error: {stderr.decode()}") raise HTTPException(status_code=500, detail=f"FFmpeg audio addition failed: {stderr.decode()}")
# Clean up temporary files for file in video_files: for file in image_files: os.remove(file) os.remove(concat_list_path) os.remove(concat_output) os.remove(music_file) os.remove(images_list_path) os.remove(intermediate_video) os.remove(audio_file) os.rmdir(temp_dir)
# Return the URL path to the output filemain.py+44-36