Voici le script 1 : import os import subprocess import numpy as np import uuid from…
- User
Voici le script 1 :
import os import subprocess import numpy as np import uuid from moviepy.editor import VideoFileClip from scipy.io import wavfile
Define video file extensions and the output folder
video_extensions = ['.mp4', '.mkv', '.wmv', '.avi'] output_folder = 'Output'
def calculate_loudness(audio_data, rate): """Calculate loudness using ITU-R BS.1770-4 method.""" if audio_data.ndim == 2: audio_data = np.mean(audio_data, axis=1) # convert to mono by averaging channels # Normalization constants for the ITU-R BS.1770-4 method pre_filter = np.array([1.53512485958697, -2.69169618940638, 1.19839281085285]) pre_gain = 1.0 power = 10.0 # Pre-filter audio_data = np.convolve(audio_data, pre_filter) * pre_gain # Calculate power and then LUFS mean_square = np.mean(audio_data ** 2) mean_power = mean_square ** (0.5) loudness = (1 / rate) * np.sum(mean_power ** power) lufs = -0.691 + 10 * np.log10(loudness) return lufs
def find_loudest_segments(audio_data, rate, num_segments, segment_duration, video_duration, starting_offset, ending_offset): """Find the segments with the highest loudness in the audio data.""" # Calculate the loudness of the audio file and loop over to find top segments loudness = np.array([calculate_loudness(audio_data[max(0, idx - int(rate * segment_duration)):min(len(audio_data), idx + int(rate * segment_duration))], rate) for idx in range(0, len(audio_data), int(rate * segment_duration))]) sorted_indices = np.argsort(loudness)[::-1] segments = [] for idx in sorted_indices: if len(segments) >= num_segments: break segment_start_time = idx * segment_duration if segment_start_time < starting_offset or segment_start_time + segment_duration > video_duration - ending_offset: continue segments.append(segment_start_time) return segments
def extract_segment(video_path, start_time, duration, output_path): """Use ffmpeg to extract a segment from a video.""" command = [ "ffmpeg", "-y", # Overwrite output files without asking "-ss", str(start_time), # Start time "-i", video_path, # Input file "-t", str(duration), # Duration "-c", "copy", # Copy the streams without re-encoding output_path # Output path ] try: subprocess.run(command, check=True, stderr=subprocess.PIPE) except subprocess.CalledProcessError as e: print(f"ffmpeg command failed: {e.stderr.decode()}")
def process_video_file(video_path, starting_offset, ending_offset, num_segments, segment_duration): """Process a single video file to find and extract the loudest segments.""" unique_id = str(uuid.uuid4()) audio_filename = f'temp_audio_{unique_id}.wav' try: video_clip = VideoFileClip(video_path) video_duration = video_clip.duration
video_clip.audio.write_audiofile(audio_filename) rate, audio_data = wavfile.read(audio_filename) segments = find_loudest_segments(audio_data, rate, num_segments, segment_duration, video_duration, starting_offset, ending_offset) if not os.path.exists(output_folder): os.makedirs(output_folder) for i, start_time in enumerate(segments): output_filename = f"{os.path.splitext(os.path.basename(video_path))[0]}_segment{i+1}.mp4" output_path = os.path.join(output_folder, output_filename) extract_segment(video_path, start_time, segment_duration, output_path) print(f"Extracted segment to {output_path}") finally: os.unlink(audio_filename) # Clean up the temporary file - Assistant
Le script Python donné est conçu pour extraire des segments sonores spécifiquement bruyants à partir de fichiers vidéo. Voici une analyse étape par étape de ce que le script réalise et comment il fonctionne :
- User
- Assistant
- User
Je voudrais que tu fasses une version améliorée du script 2, en t'inspirant du script 1.
Dans la version améliorée du script 2 :
- On supprime le calcul du moment fort avec RMS ou Pic ;
- On reprend la méthode ITU-R BS.1770-4 du script 1 et on l'implémente par défaut dans le script 2 ;
- Les autres fonctions du script 2 doivent toujours fonctionner ;
Apporte les modifications et écris l'intégralité du code du script amélioré, sans rien omettre.
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.