Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

Ce script ne s'arrête pas une fois le nombre décidé par l'utilisateur atteint : import…

  1. User

    Ce script ne s'arrête pas une fois le nombre décidé par l'utilisateur atteint :

    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 each segment in the audio file segment_loudness = [ calculate_loudness( audio_data[max(0, i * int(rate * segment_duration)) : min(len(audio_data), (i + 1) * int(rate * segment_duration))], rate) for i in range(0, int(video_duration / segment_duration)) ]

    # Combine segment start times with their corresponding loudness
    loudness_and_segments = [
        (segment_loudness[i], i * segment_duration)
        for i in range(len(segment_loudness))
        if i * segment_duration >= starting_offset and (i + 1) * segment_duration <= video_duration - ending_offset
    ]
    
    # Sort the loudness and segments based on loudness
    loudness_and_segments.sort(key=lambda x: x[0], reverse=True)
    
    # Return the top num_segments segments sorted by loudness
    return loudness_and_segments[:num_segments]
    

    def find_sound_amplitude_peak(audio_data): """Find the position of the highest sound amplitude peak.""" peak_position = np.argmax(np.abs(audio_data)) return peak_position

    def sort_segments(segments_with_loudness, preference): if preference == 1: return sorted(segments_with_loudness, key=lambda x: x[1]) elif preference == 2: return sorted(segments_with_loudness, key=lambda x: x[1], reverse=True) elif preference == 3: return sorted(segments_with_loudness, key=lambda x: x[0]) elif preference == 4: return sorted(segments_with_loudness, key=lambda x: x[0], reverse=True)

    def extract_segment(video_path, start_time, duration, output_path): """Use ffmpeg to extract a segment from a video with x264 encoding.""" command = [ "ffmpeg", "-y", # Overwrite output files without asking "-ss", str(start_time), # Start time "-i", video_path, # Input file "-t", str(duration), # Duration "-c:v", "libx264", # Use x264 video codec "-c:a", "aac", # AAC audio codec "-strict", "experimental", # Allow experimental codecs (if necessary for AAC) 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 extract_adjusted_segment(video_path, start_time, duration, output_path, rate, audio_data, peak_position_preference, segment_duration): """Adjust the start time of the segment to position the sound peak where the user wants it.""" peak_position = find_sound_amplitude_peak(audio_data) desired_peak_position = int(segment_duration * peak_position_preference / 6 * rate) adjusted_start_time = max(start_time + (peak_position - desired_peak_position) / rate, 0) extract_segment(video_path, adjusted_start_time, duration, output_path)

    def process_video_file(video_path, starting_offset, ending_offset, num_segments, segment_duration, preference, peak_position_preference): """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_with_loudness = find_loudest_segments(audio_data, rate, num_segments, segment_duration, video_duration, starting_offset, ending_offset)
    
        # Trier les segments en fonction de la préférence de l'utilisateur
        sorted_segments = sort_segments(segments_with_loudness, preference)
        
        # Anticiper si les noms de fichiers doivent correspondre à l'ordre initial
        if preference in [1, 2]:
            initial_order_index = {start_time: i for i, (loudness, start_time) in enumerate(segments_with_loudness)}
    
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)
    
        for segment in sorted_segments:
            loudness, start_time = segment
            segment_index = initial_order_index[start_time] if preference in [1, 2] else sorted_segments.index(segment)
            output_filename = f"{os.path.splitext(os.path.basename(video_path))[0]}_segment{segment_index+1}.mp4"
            output_path = os.path.join(output_folder, output_filename)
            segment_audio = audio_data[int(start_time*rate):int((start_time+segment_duration)*rate)]
    
            extract_adjusted_segment(video_path, start_time, segment_duration, output_path, rate, segment_audio, peak_position_preference, segment_duration)
            print(f"Extracted and adjusted segment to {output_path}")
    
    finally:
        if os.path.exists(audio_filename):
            os.unlink(audio_filename)  # Clean up the temporary file
    

    Main

    if name == "main": starting_offset = float(input("Start offset (sec)? ")) ending_offset = float(input("End offset (sec)? ")) num_segments = int(input("How many segments to extract? ")) segment_duration = float(input("Duration of each segment (sec)? ")) print("Choose your sorting preference for the extracted files:") print("1 - In order of appearance in the video") print("2 - In reverse order of appearance") print("3 - By increasing loudness") print("4 - By decreasing loudness") preference = int(input("Enter the number of your preference: ")) # Validate the user's preference if preference not in [1, 2, 3, 4]: print("Invalid preference. Please enter a valid number.") exit(1) # Nouveau prompt pour la position du pic sonore print("Choose the position for the maximum sound amplitude peak:") print("1 - at 1/6 of the segment playback time") print("2 - at 2/6 of the segment playback time") print("3 - at 3/6 of the segment playback time") print("4 - at 4/6 of the segment playback time") print("5 - at 5/6 of the segment playback time") peak_position_preference = int(input("Enter the number of your preference (1-6): ")) # Validate the user’s preference if peak_position_preference not in range(1, 7): print("Invalid preference. Please enter a number between 1 and 6.") exit(1)

    for root, dirs, files in os.walk('.'):
        for file in files:
            if any(file.lower().endswith(ext) for ext in video_extensions):
                video_path = os.path.join(root, file)
                print(f"Processing video {video_path}…")
                process_video_file(video_path, starting_offset, ending_offset, num_segments, segment_duration, preference, peak_position_preference)
    
    print("All videos have been processed.")
    
  2. Assistant

    The script provided is designed to extract video segments based on their loudness from video files within the current directory. It prompts the user for several parameters via the console such as the number of segments to extract, the duration of each segment, and preferences regarding the sorting of the output and position of sound amplitude peak within the segments.

    The reason the script doesn't stop after reaching the user-decided number of segments (num_segments) is that it loops through all video files in the current directory and applies the process to each one of them. The num_segments is respected for each individual video file processed.

    If you're experiencing that the script continues to run after you expect it to stop, ensure that:

    1. The user input for num_segments is correctly converting to an integer and reflects the desired number of segments you want to be extracted from each video.

    2. If you want to process only a single video or a specific subset of videos, you need to adjust the loop logic accordingly. For example, if you want the script to only process a single file, you'll need to remove or adjust the for-loop that iterates through the files.

    Keep in mind that the script, as is, is designed to process multiple video files in a directory, and 'stopping' isn't defined by extracting a set number of segments from all files combined but rather by reaching the end of the files list.

    In summary, the script should stop on its own after processing all video files in the directory, respecting the num_segments count for each individual video file. If it doesn't, there might be an error in the script, or it could be stuck in an infinite loop if there's a logical error not shown in the code.

    To diagnose further, you might need to insert debug print statements or use a debugger to step through the code and see where it's not behaving as expected. If you want to process a limited number of videos or a specific video, you will need to modify the file loop logic.

  3. User

    peut-on faire en sorte qu'il ne scanne pas les sous-dossiers ?

  4. Assistant

    Oui, vous pouvez modifier le script pour qu'il ne scanne pas les sous-dossiers lors de la recherche de fichiers vidéo. Pour cela, vous devez remplacer la boucle actuelle qui utilise os.walk('.'), laquelle parcourt récursivement le dossier actuel et ses sous-dossiers, par une simple itération sur les fichiers du répertoire courant.

    Vous pouvez utiliser os.listdir('.') ou une compréhension de liste pour filtrer les fichiers selon les extensions souhaitées. Voici comment vous pourriez modifier la boucle principale pour que le script n'analyse que les fichiers vidéo dans le dossier courant:

    # Main
    if __name__ == "__main__":
        # (Votre code existant pour le dialogue avec l'utilisateur)
    
        # Récupérer la liste des fichiers dans le répertoire courant
        files = os.listdir('.')
    
        # Traiter chaque fichier dans la liste
        for file in files:
            # Vérifier si le fichier est un fichier vidéo en fonction de l'extension
            if any(file.lower().endswith(ext) for ext in video_extensions):
                # Construire le chemin complet vers le fichier vidéo
                video_path = os.path.join('.', file)
                print(f"Processing video {video_path}…")
                # Appel à la fonction existante de traitement du fichier vidéo
                process_video_file(video_path, starting_offset, ending_offset, num_segments, segment_duration, preference, peak_position_preference)
    
        print("All videos have been processed.")
    

    En utilisant os.listdir('.'), nous limitons la recherche aux fichiers et dossiers du répertoire courant .. Les sous-dossiers ne seront pas explorés. Notez que os.listdir() renvoie à la fois des fichiers et des dossiers, donc si vous avez des dossiers qui correspondent aux extensions de fichiers vidéo, il se pourrait qu'ils soient inclus dans le traitement. Toutefois, le script tel qu'il est conçu actuellement ne traitera que des fichiers valides puisque VideoFileClip échouera avec un répertoire.

    Aussi, os.path.join('.', file) est équivalent à juste file, mais il est utile de construire explicitement des chemins avec os.path.join pour assurer une bonne portabilité et une cohérence dans la manipulation des chemins de fichiers.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.