Ahmadkhan12's picture
Update app.py
dabc55d verified
raw
history blame
2.71 kB
import os
import random
import ffmpeg
import gradio as gr
import traceback
# Function to add music to video
def add_music_to_video(video_path, chunks_folder="chunks", output_path="output_with_music.mp4"):
try:
# List all MP3 files in the chunks folder
if not os.path.exists(chunks_folder):
return "Error: Chunks folder does not exist."
music_files = [os.path.join(chunks_folder, f) for f in os.listdir(chunks_folder) if f.endswith('.mp3')]
if not music_files:
return "Error: No audio files found in the chunks folder."
# Randomly select one MP3 file
music_file_path = random.choice(music_files)
print(f"Selected music file: {music_file_path}")
# Get the duration of the video
video_info = ffmpeg.probe(video_path)
video_duration = float(video_info['streams'][0]['duration'])
print(f"Video duration: {video_duration} seconds")
# Trim the music file to match the video duration
trimmed_music_path = "trimmed_music.mp3"
ffmpeg.input(music_file_path).output(
trimmed_music_path, ss=0, t=video_duration
).run(overwrite_output=True)
print(f"Trimmed music saved at: {trimmed_music_path}")
# Combine video and audio
video_input = ffmpeg.input(video_path)
audio_input = ffmpeg.input(trimmed_music_path)
ffmpeg.concat(video_input, audio_input, v=1, a=1).output(
output_path, vcodec="libx264", acodec="aac", strict="experimental"
).run(overwrite_output=True)
print(f"Output video saved at: {output_path}")
return output_path
except Exception as e:
print("Error during processing:", e)
traceback.print_exc()
return f"Error: {str(e)}"
# Define Gradio interface
def process_video(uploaded_video):
try:
print("Video received for processing.")
video_path = uploaded_video.name
print(f"Uploaded video path: {video_path}")
output_video = add_music_to_video(video_path, chunks_folder="/content/chunks")
if "Error" in output_video:
return output_video
return output_video
except Exception as e:
print("Error in process_video:", e)
traceback.print_exc()
return f"Error: {str(e)}"
# Gradio Interface
interface = gr.Interface(
fn=process_video,
inputs=gr.Video(label="Upload Video"),
outputs=gr.Video(label="Video with Background Music"),
title="Add Background Music to Video",
description="Upload a video, and this app will add a background music track that matches the video duration."
)
# Launch Gradio app
interface.launch(share=True, debug=True)