import os import subprocess import numpy as np import uuid from moviepy.editor import…
- User
import os import subprocess import numpy as np import uuid from moviepy.editor import VideoFileClip from scipy.io import wavfile import random
video_extensions = ['.mp4', '.mkv', '.wmv', '.avi'] output_folder = 'Output'
def calculate_loudness(audio_data): if audio_data.ndim == 1: volume = audio_data ** 2 else: volume = np.mean(audio_data ** 2, axis=1) return np.sqrt(volume)
def find_loudest_moments(audio_filename, num_moments, segment_duration, video_duration, starting_offset, ending_offset): rate, audio_data = wavfile.read(audio_filename) if audio_data.ndim == 2: audio_data = np.mean(audio_data, axis=1) volume = calculate_loudness(audio_data.astype('float32'))
start_index = int(starting_offset * rate) end_index = int((video_duration - ending_offset) * rate) moments = [] while len(moments) < num_moments: index = np.argmax(volume[start_index:end_index]) moment = (start_index + index) / rate # Skip moments too close to the start or end if moment - segment_duration / 2 < starting_offset or moment + segment_duration / 2 > video_duration - ending_offset: volume[start_index + index] = 0 continue moments.append(moment) # Clear out the volume data around the found moment to avoid overlap clear_margin = int(segment_duration * rate / 2) clear_start = max(start_index, start_index + index - clear_margin) clear_end = min(end_index, start_index + index + clear_margin) volume[clear_start:clear_end] = 0 return sorted(moments)def ask_peak_position(): print("Choisissez le positionnement du pic sonore dans le segment vidéo :") print("1 - En début de vidéo (à un tiers)") print("2 - Au milieu de la vidéo") print("3 - En fin de vidéo (aux deux tiers)") print("4 - Aléatoire (à un tiers, au milieu, ou aux deux tiers)") choice = input("Entrez le numéro de votre choix : ")
while choice not in ('1', '2', '3', '4'): print("Entrée invalide. Veuillez choisir une option valide.") choice = input("Entrez le numéro de votre choix : ") return int(choice)def extract_segments(video_path, moments, segment_duration, peak_position_choice): if not os.path.exists(output_folder): os.makedirs(output_folder) base_name = os.path.splitext(os.path.basename(video_path))[0] video_duration = VideoFileClip(video_path).duration
for i, moment in enumerate(moments): if peak_position_choice == 1: # Start of video start_time = max(moment - segment_duration / 3, 0) elif peak_position_choice == 2: # Middle of video start_time = max(moment - segment_duration / 2, 0) elif peak_position_choice == 3: # End of video start_time = max(moment - 2 * segment_duration / 3, 0) elif peak_position_choice == 4: # Random start_time = max(moment - segment_duration * random.choice([1/3, 1/2, 2/3]), 0) else: raise ValueError("Invalid peak position choice") 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", "-ss", str(start_time), "-i", video_path, "-t", str(min(segment_duration, video_duration - start_time)), "-c:v", "libx264", "-preset", "medium", "-crf", "23", "-c:a", "aac", "-strict", "-2", "-b:a", "192k", output_path ] subprocess.run(command, check=True, stderr=subprocess.PIPE) print(f"Extracted and re-encoded {output_filename}") - Assistant
The provided script is designed to process video files within a directory, extract segments based on the loudness of the audio track, and then re-encode those segments into separate video files. It consists of several functions that handle different parts of the process:
- User
Combien de secondes à ignorer au début pour l’analyse ? 0 Combien de secondes à ignorer à la fin pour l’analyse ? 0 Quelle est la durée (en secondes) de chaque segment vidéo à extraire ? 10 Choisissez le positionnement du pic sonore dans le segment vidéo : 1 - En début de vidéo (à un tiers) 2 - Au milieu de la vidéo 3 - En fin de vidéo (aux deux tiers) 4 - Aléatoire (à un tiers, au milieu, ou aux deux tiers) Entrez le numéro de votre choix : 2 Voulez-vous que le script fonctionne en : 1 - Autopilote (extraire tous les moments forts) 2 - Spécifier le nombre de moments forts Entrez le numéro de votre choix : 2 Combien de moments forts souhaiteriez-vous extraire de chaque vidéo ? 30 MoviePy - Writing audio in temp_audioa2f46e02-c129-423f-8a29-e7c5a2e61cce.wav MoviePy - Done. Traceback (most recent call last): File “H:\Tests\Script Final V6 - choix 2.py”, line 154, in process_video_files(starting_offset_seconds, ending_offset_seconds, num_moments, segment_duration, peak_position_choice, autopilot) File “H:\Tests\Script Final V6 - choix 2.py”, line 134, in process_video_files extract_segments(video_path, moments, segment_duration, peak_position_choice) File “H:\Tests\Script Final V6 - choix 2.py”, line 95, in extract_segments end_time = min(start_time + segment_duration, video_clip.duration) ^^^^^^^^^^ NameError: name ‘video_clip’ is not defined
- Assistant
It looks like the error is due to a variable
video_clipthat is referenced in theextract_segments()function but not defined within its scope. This variable seems to be used to determine the video's duration. However, instead ofvideo_clip.duration, the variablevideo_durationwhich is already calculated and passed to the function should be used. - User
réécris tout le script dans son intégralité stp, sans rien oublier du tout
- Assistant
- User
Laisse le choix en début de script à l’utilisateur pour les moments forts :
1- Autopilote 2- Spécifier le nombre de moments forts
Si l’utilisateur choisit 1- Autopilote, tout les moments forts sont extraits. S’il choisit 2- Spécifier, on le laisse renseigner le nombre de moments à conserver.
Réécris tout le script sans rien oublier stp, dans son intégralité
- Assistant
- User
Traceback (most recent call last): File "H:\Tests\Script V7 - choix.py", line 145, in process_video_files(starting_offset_seconds, ending_offset_seconds, segment_duration, peak_position_choice, autopilot_mode, num_moments) File "H:\Tests\Script V7 - choix.py", line 113, in process_video_files moments = autopilot_seek_moments(audio_path, segment_duration, video_duration, starting_offset_seconds, ending_offset_seconds) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "H:\Tests\Script V7 - choix.py", line 61, in autopilot_seek_moments return find_loudest_moments(audio_filename, num_segments, segment_duration, video_duration, starting_offset, ending_offset) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "H:\Tests\Script V7 - choix.py", line 29, in find_loudest_moments average_loudness_per_window = np.array([loudness[i:i+window_size].mean() for i in range(0, len(loudness) - window_size, window_size)]) ^^^^^^^^^^^^^ TypeError: object of type 'numpy.float32' has no len()
- Assistant
Apologies for the oversight. The error is due to
loudnessbeing a single float value instead of an array. I mistakenly replaced the volume array with the average loudness scalar in thecalculate_loudnessfunction. Let's correct the error and rewrite thecalculate_loudnessand functions. I will ensure the rest of the script is unchanged. - User
réécris tout le script stp, sans rien oublier du tout
- Assistant
- User
Traceback (most recent call last): File "H:\Tests\Script V7 - choix.py", line 143, in main() File "H:\Tests\Script V7 - choix.py", line 140, in main process_video_files(starting_offset_seconds, ending_offset_seconds, segment_duration, peak_position_choice, num_moments) File "H:\Tests\Script V7 - choix.py", line 108, in process_video_files moments = find_loudest_moments(audio_path, num_potential_segments, segment_duration, video_duration, starting_offset_seconds, ending_offset_seconds) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "H:\Tests\Script V7 - choix.py", line 23, in find_loudest_moments num_samples = loudness.shape[0] ~~~~~~~~~~~~~~^^^ IndexError: tuple index out of range
- Assistant
- User
réécris l'intégralité, sans rien oublier du tout stp
- Assistant
- User
Traceback (most recent call last): File "H:\Tests\Script V7 - choix.py", line 143, in main() File "H:\Tests\Script V7 - choix.py", line 140, in main process_video_files(starting_offset_seconds, ending_offset_seconds, segment_duration, peak_position_choice, num_moments) File "H:\Tests\Script V7 - choix.py", line 110, in process_video_files moments = find_loudest_moments(audio_path, num_moments, segment_duration, video_duration, starting_offset_seconds, ending_offset_seconds) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "H:\Tests\Script V7 - choix.py", line 30, in find_loudest_moments num_segments = len(loudness) // segment_length ^^^^^^^^^^^^^ TypeError: object of type 'numpy.float64' has no len()
- Assistant
- User
Traceback (most recent call last): File "H:\Tests\Script V7 - choix.py", line 114, in process_video_files(starting_offset_seconds, ending_offset_seconds, segment_duration, peak_position_choice, autopilot_mode) File "H:\Tests\Script V7 - choix.py", line 86, in process_video_files moments = find_loudest_moments(audio_path, num_moments, segment_duration, video_clip.duration, starting_offset_seconds, ending_offset_seconds, rate) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "H:\Tests\Script V7 - choix.py", line 26, in find_loudest_moments windowed_loudness = np.lib.stride_tricks.sliding_window_view(loudness, window_shape=segment_samples)[::segment_samples] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jp\AppData\Local\Programs\Python\Python312\Lib\site-packages\numpy\lib\stride_tricks.py", line 315, in sliding_window_view raise ValueError(f'Since axis is
None, must provide ' ValueError: Since axis isNone, must provide window_shape for all dimensions ofx; got 1 window_shape elements andx.ndimis 0. - Assistant
- User
- Assistant
- User
la fonction find loudest moments ne permet pas le chevauchement ?
- Assistant
- User
Peux-tu ajouter cette fonction dans le script ?
Je voudrais aussi que le choix soit laissé à l'utilisateur en début de script :
"Voulez-vous permettre le chevauchement lors de la recherche des moments ?" 1-Oui 2-Non
Réécris l'intégralité du script, sans absolument rien omettre
- Assistant
- User
Do you want to allow overlap in the search for moments? 1 - Yes 2 - No Enter the number of your choice: 2 Do you want the script to run in autopilot mode? (yes or no): yes Processing .\7113b3eebd081dd638f22df8b4c6760d2ebabdd8ee657b7c12cf8a690e514591.mp4 MoviePy - Writing audio in temp_audio03728d57-a43a-4937-ad2b-0a04bd664566.wav MoviePy - Done. Traceback (most recent call last): File "H:\Tests\Script V7 - choix.py", line 144, in main() File "H:\Tests\Script V7 - choix.py", line 139, in main process_video_files(starting_offset_seconds, ending_offset_seconds, segment_duration, peak_position_choice, allow_overlap, autopilot_mode, num_moments) File "H:\Tests\Script V7 - choix.py", line 113, in process_video_files moments = find_loudest_moments( ^^^^^^^^^^^^^^^^^^^^^ File "H:\Tests\Script V7 - choix.py", line 36, in find_loudest_moments loudness = loudness[:len(loudness)-len(loudness)%num_samples_per_segment] # Trim to make length multiple of num_samples_per_segment ^^^^^^^^^^^^^ TypeError: object of type 'numpy.float64' has no len()
- Assistant
- User
Je voudrais aussi que tu changes la question pour l'autopilote, en mettant 1- Oui 2-Non plutôt que yes ou no. réécris tout le script en intégralité, en n'oubliant rien stp.
- Assistant
- User
Traceback (most recent call last): File "H:\Tests\Script V7 - choix.py", line 147, in main() File "H:\Tests\Script V7 - choix.py", line 143, in main process_video_files(starting_offset_seconds, ending_offset_seconds, segment_duration, peak_position_choice, allow_overlap, autopilot_mode, num_moments) File "H:\Tests\Script V7 - choix.py", line 124, in process_video_files moments = find_loudest_moments(audio_path, num_moments, segment_duration, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "H:\Tests\Script V7 - choix.py", line 25, in find_loudest_moments _, audio_data = wavfile.read(audio_filename) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jp\AppData\Local\Programs\Python\Python312\Lib\site-packages\scipy\io\wavfile.py", line 647, in read fid = open(filename, 'rb') ^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: 'temp_audioac7d59e4-c5b8-43b7-b7d0-4e7a342a5b7c.wav'
- Assistant
- User
Peux-tu réécrire tout le script dans son intégralité, sans rien oublier ?
- Assistant
- User
Traceback (most recent call last): File "H:\Tests\Script V7 - choix.py", line 137, in main() File "H:\Tests\Script V7 - choix.py", line 132, in main process_video_files(starting_offset_seconds, ending_offset_seconds, segment_duration, peak_position_choice, allow_overlap, autopilot_mode, num_moments) File "H:\Tests\Script V7 - choix.py", line 110, in process_video_files moments = find_loudest_moments(audio_data, num_moments, segment_duration, video_duration, starting_offset_seconds, ending_offset_seconds, rate, allow_overlap) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "H:\Tests\Script V7 - choix.py", line 29, in find_loudest_moments loudest_indices = np.argsort(convolved_loudness)[-num_moments:] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^ TypeError: slice indices must be integers or None or have an index method
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.