CoolFace
Apppublic

gnosticdev/image_dubbing

sourceHugging Faceapache-2.0updated 2y agoView on Hugging Face
0likes
app.py136 linesDownload Raw Back to root
1import cv22import numpy as np3from pydub import AudioSegment4from moviepy.editor import VideoFileClip, AudioFileClip5 6 7 8def image_to_video(image_path, video_path,audio_path,  fps=30):9    """10    Converts an image into a video of specified duration.11 12    Parameters:13    - image_path: Path to the input image.14    - video_path: Path where the output video will be saved.15    - duration_sec: Duration of the video in seconds.16    - fps: Frames per second of the output video.17    """18    # Load the image19    print("image_path",image_path)20    img = cv2.imread(image_path)21    print("image_path")22    if img is None:23        raise ValueError("Image could not be loaded. Please check the path.")24 25 26    # Get image dimensions27    height, width, layers = img.shape28 29    # Define the codec and create VideoWriter object30    fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # Use 'XVID' if you prefer AVI format31    video = cv2.VideoWriter(video_path, fourcc, fps, (width, height))32 33    audio = AudioSegment.from_file(audio_path)34    duration_sec = len(audio) / 1000.0  # Duration in milliseconds to seconds35 36 37    # Calculate the number of frames needed to achieve the desired duration38    num_frames = duration_sec * fps39 40    # Write the image to video file for the required number of frames41    for _ in range(int(num_frames)):42        video.write(img)43 44    # Release the video writer45    video.release()46 47    video_clip = VideoFileClip(video_path)48    audio_clip = AudioFileClip(audio_path)49    final_clip = video_clip.set_audio(audio_clip)50    final_clip.write_videofile(video_path, codec="libx264", audio_codec="aac")51    return video_path52 53def rename():54    import os55    import shutil56 57    # Define the directory to search in58    directory = os.getcwd()59 60    # Initialize variables for the first .jpg and .wav files found61    first_jpg_file = None62    first_wav_file = None63 64    # Search for the first .jpg and .wav files in the directory65    for filename in os.listdir(directory):66        if filename.endswith('.jpg') and first_jpg_file is None:67            first_jpg_file = os.path.join(directory, filename)68        elif filename.endswith('.wav') and first_wav_file is None:69            first_wav_file = os.path.join(directory, filename)70            print(f"Audio file renamed to {audio_path_new}")71 72 73    # New paths with desired names74    image_path_new = os.path.join(directory, 'logo.jpg')75    audio_path_new = os.path.join(directory, 'audio.wav')76    print(f"Image file renamed to {image_path_new}")77 78    # Rename (or move) the image file if found79    if first_jpg_file:80        shutil.move(first_jpg_file, image_path_new)81        print(f"Image file renamed to {image_path_new}")82    else:83        print("No .jpg file found.")84 85 86 87    # Rename (or move) the audio file if found88    if first_wav_file:89        shutil.move(first_wav_file, audio_path_new)90        print(f"Audio file renamed to {audio_path_new}")91    else:92        print("No .wav file found.")93 94    return  image_path_new,audio_path_new95 96 97 98# Example usage99def image_audio_to_video(image_path, audio_path):100  101  import os102  dir=os.getcwd()103  print("dir",dir)104  video_path=f"/{dir}/video.mp4"105  print("video_path",video_path)106  image_to_video(image_path, video_path,audio_path)107  return video_path108 109import gradio as gr110def setup_interface():111    """112    Setup and launch the Gradio interface.113    """114    with gr.Blocks() as demo:115        gr.Markdown("## Create a Video from an Image and Audio")116        with gr.Row():117            with gr.Column():118                image_upload = gr.Image(label="Upload Image",type="filepath")119                audio_upload = gr.Audio(label="Upload Audio",type="filepath")120            with gr.Column():121                output_video = gr.Video(label="Output Video")122 123        # Button to initiate the process124        if image_upload and audio_upload :125          submit_btn = gr.Button("Create Video")126 127          # Function call on button press with both image and audio as inputs128          submit_btn.click(fn=image_audio_to_video,129                          inputs=[image_upload, audio_upload],130                          outputs=output_video)131 132 133    demo.launch(show_error=True)134 135if __name__ == "__main__":136    setup_interface()