import os import subprocess import numpy as np import uuid # Import uuid to generate…
- User
import os import subprocess import numpy as np import uuid # Import uuid to generate unique IDs from moviepy.editor import VideoFileClip from scipy.io import wavfile
temporary_audio_files = []
Define video file extensions and the output folder
video_extensions = ['.mp4', '.mkv', '.wmv', '.avi'] output_folder = 'Output'
def ask_directory_preference(): print("Souhaitez-vous inclure les sous-dossiers dans la recherche des vidéos ?") print("1- Oui") print("2- Non") choice = input("Veuillez entrer le numéro de votre choix (1 ou 2) : ") return choice.strip() == '1' # Retourne True si l'utilisateur choisit '1' (Oui), False sinon
def calculate_loudness(audio_data): if audio_data.ndim == 1: volume = audio_data.astype('float32') ** 2 else: volume = np.mean(audio_data.astype('float32') ** 2, axis=1) volume_dB = 10 * np.log10(volume + 1e-9) # +1e-9 to avoid log(0) and convert to dB return volume_dB
def find_loudest_moments(audio_filename, num_moments, segment_duration, video_duration, starting_offset, ending_offset): rate, audio_data = wavfile.read(audio_filename)
# Convert stereo to mono if necessary if audio_data.ndim == 2: audio_data = np.mean(audio_data, axis=1) volume_dB = calculate_loudness(audio_data) segment_half_duration = segment_duration / 2.0 start_index = int(starting_offset * rate) end_index = int((video_duration - ending_offset) * rate) moments = [] volumes = [] while len(moments) < num_moments and (end_index - start_index) > 0: index = np.argmax(volume_dB[start_index:end_index]) moment = (start_index + index) / rate moment_volume = volume_dB[start_index + index] # Skip the moment and set its volume to a very low number if it is too close to the start or the end if moment - segment_half_duration < starting_offset or moment + segment_half_duration > video_duration - ending_offset: volume_dB[start_index + index] = -np.inf continue moments.append(moment) volumes.append(moment_volume) # Clear the volume around the found moment to prevent picking up nearby moments clear_range_start = max(0, index - int(rate * segment_half_duration)) clear_range_end = min(len(volume_dB), index + int(rate * segment_half_duration)) volume_dB[clear_range_start:clear_range_end] = -np.inf return moments, volumesdef extract_segments(video_path, moments, segment_duration, video_duration): if not os.path.exists(output_folder): os.makedirs(output_folder) base_name = os.path.splitext(os.path.basename(video_path))[0] half_segment_duration = segment_duration / 2
for i, moment in enumerate(moments): start_time = max(moment - half_segment_duration, 0) end_time = min(start_time + segment_duration, video_duration) output_filename = f"{base_name}_moment{i + 1}.mp4" output_path = os.path.join(output_folder, output_filename) command = [ "ffmpeg", "-y", # Overwrite output files without asking "-ss", str(start_time), # Start time "-i", video_path, # Input file "-t", str(min(segment_duration, video_duration - start_time)), # Duration or remaining video "-c:v", "libx264", # Specify video codec for output "-preset", "medium", # Specify the encoding preset (trade-off between encoding speed and quality) "-crf", "23", # Specify the Constant Rate Factor for quality (lower means better quality) "-c:a", "aac", # Specify audio codec for output "-strict", "-2", # Necessary for some versions of ffmpeg to use experimental aac encoder "-b:a", "192k", # Specify the audio bitrate output_path # Output path ] try: subprocess.run(command, check=True, stderr=subprocess.PIPE) print(f"Extracted and re-encoded {output_filename}") except subprocess.CalledProcessError as e: # Catch the exception for this process, print an error message, # but don't break from the for loop. err_msg = e.stderr.decode('utf-8') if e.stderr else 'Unknown error' print(f"Failed to extract segment from {video_path}: {err_msg}") - Assistant
- User
Quel est l'intervalle temporel utilisé pour l'identification pour les pics de volume ?
- Assistant
Dans le code partagé, il n'y a pas de taille d'intervalle temporel définie explicitement pour la détection des pics de volume. À la place, l'algorithme trouve les valeurs maximales de volume (en dB) dans l'ensemble du fichier audio, tout en respectant les contraintes imposées par les décalages de début (
starting_offset) et de fin (). - User
Comment peuvent être interprétés, au niveau de la manifestation sonore, les moments les plus bruyants ? En fonction du volume en dB, en fonction du pic d'amplitude ?...
- Assistant
- User
Y a-t-il un lien entre amplitude et puissance en db ?
- Assistant
Oui, il y a un lien entre l'amplitude d'un signal audio et sa puissance mesurée en décibels (dB), mais ces deux concepts ne sont pas identiques et la relation entre eux est logarithmique.
Pour clarifier:
-
Amplitude: L'amplitude fait référence à la grandeur de la variation d'un signal sonore, c'est-à-dire la hauteur de l'onde sonore. Une amplitude plus élevée signifie des variations de pression plus grandes dans l'onde sonore et peut être perçue comme un son plus fort lorsque l'oreille humaine est exposée.
-
- User
Je voudrais qu'après avoir trouvé un pic de volume, le code ne supprime pas la possibilité de trouver un autre pic trop près de celui-ci en définissant les volumes dans un intervalle autour du pic à -np.inf. Le but est que tous les pics puissent potentiellement être au centre des possibles segments à extraire.
- Assistant
- User
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.