import os import logging from logging import Logger from moviepy import VideoFileClip # Configure logging logger: Logger = logging.getLogger(__name__) def get_video_duration(video_path: str) -> float: """ Get the duration of a video file in seconds. Args: video_path (str): The path to the video file. Returns: float: The duration of the video in seconds. Raises: FileNotFoundError: If the video file does not exist. RuntimeError: If an error occurs during processing. """ if not os.path.exists(video_path): logger.error(f"Video file {video_path} does not exist.") raise FileNotFoundError(f"Video file {video_path} does not exist.") try: video_clip = VideoFileClip(video_path) duration = video_clip.duration logger.info(f"Duration of video {video_path}: {duration} seconds.") return duration except Exception as e: logger.error(f"Failed to get video duration: {e}", exc_info=True) raise RuntimeError(f"Failed to get video duration: {e}") finally: video_clip.close() def extract_audio_from_video(video_path: str, output_dir: str) -> str: """ Extracts the audio track from a video file and saves it as a WAV file. Args: video_path (str): The path to the video file. output_dir (str): The directory where the audio file will be saved. Returns: str: The path to the extracted audio file. Raises: FileNotFoundError: If the video file does not exist. RuntimeError: If an error occurs during audio extraction. """ if not os.path.exists(video_path): logger.error(f"Video file {video_path} does not exist.") raise FileNotFoundError(f"Video file {video_path} does not exist.") try: logger.info(f"Extracting audio from video: {video_path}") video_clip = VideoFileClip(video_path) audio_path = os.path.join(output_dir, f"{os.path.splitext(os.path.basename(video_path))[0]}.wav") video_clip.audio.write_audiofile(audio_path) # type: ignore logger.info(f"Audio extracted and saved to: {audio_path}") return audio_path except Exception as e: logger.error(f"Failed to extract audio from video: {e}", exc_info=True) raise RuntimeError(f"Failed to extract audio from video: {e}") finally: video_clip.close()