Ahmadkhan12's picture
Create app.py
51ed60c verified
raw
history blame
3.8 kB
import os
from random import choice
from moviepy.editor import VideoFileClip, AudioFileClip
import tempfile
import gradio as gr
# Updated music directory path (relative to the Hugging Face repo)
MUSIC_DIR = "chunks" # Path to the folder where your music files are stored on Hugging Face
DEFAULT_MUSIC = "default_music.mp3" # Optional: path to default music if you want a fallback
def load_music_files():
"""
Load all music files from the directory. Use default if no files found.
"""
try:
# Ensure directory exists and is readable
if not os.path.exists(MUSIC_DIR):
raise FileNotFoundError(f"Music directory not found: {MUSIC_DIR}")
music_files = [os.path.join(MUSIC_DIR, f) for f in os.listdir(MUSIC_DIR) if f.endswith(".mp3")]
if not music_files:
print("No music files found! Using default music.")
if not os.path.exists(DEFAULT_MUSIC):
raise FileNotFoundError("Default music file is missing!")
music_files.append(DEFAULT_MUSIC)
print(f"Loaded {len(music_files)} music files.")
return music_files
except Exception as e:
raise FileNotFoundError(f"Error loading music files: {e}")
def generate_music(scene_analysis):
"""
Select a random music file from the available files.
"""
music_files = load_music_files()
selected_music = choice(music_files) # Pick a random music file
print(f"Selected music: {selected_music}")
return selected_music
def analyze_video(video_path):
"""
Dummy scene analysis function. Replace with an actual analysis implementation.
"""
print(f"Analyzing video: {video_path}")
return {"scene_type": "Generic", "detected_objects": []}
def process_video(video_path, music_path):
"""
Combines the video with background music.
"""
try:
print(f"Processing video: {video_path} with music: {music_path}")
video_clip = VideoFileClip(video_path)
music_clip = AudioFileClip(music_path)
# Trim music to match video duration
music_clip = music_clip.subclip(0, min(video_clip.duration, music_clip.duration))
# Add music to video
final_video = video_clip.set_audio(music_clip)
# Save the processed video
output_path = tempfile.mktemp(suffix=".mp4")
final_video.write_videofile(output_path, codec="libx264", audio_codec="aac")
return output_path
except Exception as e:
print(f"Error in process_video: {e}")
raise e
def main(video_path):
try:
analysis = analyze_video(video_path)
music_path = generate_music(analysis) # Get a fresh music track every time
output_path = process_video(video_path, music_path)
return output_path, f"Music file used: {os.path.basename(music_path)}"
except Exception as e:
print(f"Error in main: {e}")
return None, f"Error: {e}"
# Gradio Interface
def gradio_interface(video_file):
output_path, message = main(video_file)
if output_path:
return output_path, message
else:
return None, message
iface = gr.Interface(
fn=gradio_interface,
inputs=gr.Video(label="Upload Video"),
outputs=[
gr.Video(label="Processed Video"),
gr.Textbox(label="Result Info"),
],
title="Music Video Processor",
description="Upload a video, and it will randomly select one of the uploaded or default music files to combine with the video."
)
# Optional: Download default music if it's not included in your Hugging Face repo
if not os.path.exists(DEFAULT_MUSIC):
print("Downloading default music...")
os.system('wget -O default_music.mp3 "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"')
iface.launch(debug=True)