# Miris Chrismas list

    from pathlib import Path
    cd1=Path('/home/dl92/Music/cd#1')
    cd2=Path('/home/dl92/Music/cd#2')

    from pydub import AudioSegment

    for fname in cd1.glob('**/*.wav'):
        song = AudioSegment.frfrom_wav(fname)
        #print(fname.stem)
        fname_mp3=fname.parent/'mp3'/f'{fname.stem}.mp3'
        print(fname_mp3)
        song.export(fname_mp3,format='mp3')

    ---------------------------------------------------------------------------
    ModuleNotFoundError                       Traceback (most recent call last)
    /home/ys/Data/projects/code/Python/Scripts/audioconversion.ipynb Cell 2 line 1
    ----> <a href='vscode-notebook-cell:/home/ys/Data/projects/code/Python/Scripts/audioconversion.ipynb#W1sZmlsZQ%3D%3D?line=0'>1</a> from pydub import AudioSegment
          <a href='vscode-notebook-cell:/home/ys/Data/projects/code/Python/Scripts/audioconversion.ipynb#W1sZmlsZQ%3D%3D?line=2'>3</a> for fname in cd1.glob('**/*.wav'):
          <a href='vscode-notebook-cell:/home/ys/Data/projects/code/Python/Scripts/audioconversion.ipynb#W1sZmlsZQ%3D%3D?line=3'>4</a>     song = AudioSegment.frfrom_wav(fname)

    ModuleNotFoundError: No module named 'pydub'

    import pytube
    from pytube import YouTube

    #yt=YouTube('https://www.youtube.com/watch?v=M73x3O7dhmg')#philip glass
    #yt=YouTube('https://www.youtube.com/watch?v=K3RjISiW7gA')#Reinhardt - The Best of Jazz Guitar (The Greatest Jazz Masterpieces) [Standard Jazz Tracks].
    yt=YouTube('https://www.youtube.com/watch?v=Ty4isRlrrbg')
    yt=YouTube('https://www.youtube.com/watch?v=G6kAmdzfvC8')
    #yt.streaming_data
    (print(yt.streams
           #.filter(res='720p',mime_type='video/mp4')
           .filter(progressive=True,mime_type='video/mp4')
           )

    #.desc()
    )

    Running cells with 'General' requires the ipykernel package.

    Run the following command to install 'ipykernel' into the Python environment.

    Command: '/home/ys/Data/devtools/Envs/General/bin/python3.10 -m pip install ipykernel -U --force-reinstall'

    from pytube import YouTube
    import moviepy.editor as mp
    from youtube_transcript_api import YouTubeTranscriptApi

    def remove_timestamps(transcript):
      """
      Removes timestamps from a transcript string.

      Args:
          transcript: A string containing the transcript with timestamps.

      Returns:
          A string containing the transcript without timestamps.
      """
      clean_transcript = ""
      for line in transcript.splitlines():
        # Check if the line starts with a timestamp
        if line.startswith("["):
          # Split the line to separate the timestamp and text
          timestamp, text = line.split("] ")
          # Add only the text to the clean transcript
          clean_transcript += text + "\n"
        else:
          # Add the entire line to the clean transcript
          clean_transcript += line + "\n"
      return clean_transcript.strip()

    def convert_mp4_to_mp3(video_path):
      """
      This function converts an MP4 video to an MP3 audio file.

      Args:
          video_path: The path to the MP4 video file.
          audio_path: The path where you want to save the extracted MP3 audio file.
      """
      try:
        # Load the video file
        video = mp.VideoFileClip(video_path)
        bb=video_path.split('.')[0]
        audio_path=f'{bb}.mp3'
        # Extract the audio from the video and save it as an MP3 file
        video.audio.write_audiofile(audio_path)

        # Print a success message
        print(f"Audio extracted and saved as: {audio_path}")
      except Exception as e:
        print(f"Error converting MP4 to MP3: {e}")

    def download_mp4(video_url, output_path="video.mp4", resolution="720p"):
      """
      Downloads an MP4 video from YouTube.

      Args:
        video_url: The URL of the YouTube video.
        output_path: The path to save the downloaded video.
        resolution: The resolution of the video to download (default: 720p).
      """
      try:
        # Get the YouTube object
        yt = YouTube(video_url)

        # Get video title and language
        title = yt.title
        print (title)
        #lang = yt.captions.all().get('en').language_code

        # Use youtube_transcript_api to retrieve transcript
        transcript = YouTubeTranscriptApi.get_transcript(yt.video_id)

        # Access transcript data
        text = transcript[0]['text']
        start_seconds = transcript[0]['start']
        end_seconds = start_seconds+transcript[0]['duration']

        # Print transcript information
        print(f"Video title: {title}")

        # Loop through each transcript segment and print text with timestamps
        for segment in transcript:
            start_seconds = segment['start']
            end_seconds = start_seconds+segment['duration']
            print(segment['text'])
            #print(f"[{segment['start']} - {end_seconds}] {segment['text']}")

        # Choose the video stream with the desired resolution
        video_stream = yt.streams.filter(progressive=True, resolution=resolution).first()

        # Download the video
        video_stream.download(filename=output_path)

        print(f"Video downloaded to: {output_path}")
      except Exception as e:
        print(f"Error downloading video: {e}")

    # Example usage
    #video_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
    #video_url ='https://www.youtube.com/watch?v=eNhJY-R3Gwg'
    #download_mp4(video_url)
    #convert_mp4_to_mp3('video.mp4')

    from pathlib import Path
    from pytube import YouTube
    import moviepy.editor as mp
    from youtube_transcript_api import YouTubeTranscriptApi
    from pathvalidate import sanitize_filepath

    #print(oppath/'wav')
    def convert_mp4_to_mp3(file,oppath):
        try:
        # Load the video file
            #video = mp.VideoFileClip(file)
            audio=mp.AudioFileClip(str(file))
            stem=str(file.stem)#.replace.rstrip().lstrip()
            audio_path=sanitize_filepath(oppath/'mp3'/f'{stem}.mp3')
            print('audio_path', stem, audio_path)
            # Extract the audio from the video and save it as an MP3 file
            #video.audio.write_audiofile(audio_path, codec='pcm_s16le')
            audio.write_audiofile(str(audio_path),write_logfile=True,verbose=True)#, codec='pcm_s16le')

            # Print a success message
            print(f"Audio extracted and saved as: {audio_path}")
        except Exception as e:
            print(f"Error converting MP4 to MP3: {e}")

    def convert_mp4_to_wav(file,oppath):
        try:
        # Load the video file
            #video = mp.VideoFileClip(file)
            audio=mp.AudioFileClip(str(file))
            stem=str(file.stem)#.replace.rstrip().lstrip()
            audio_path=sanitize_filepath(oppath/'wav'/f'{stem}.wav')
            print('audio_path', stem, audio_path)
            # Extract the audio from the video and save it as an MP3 file
            #video.audio.write_audiofile(audio_path, codec='pcm_s16le')
            audio.write_audiofile(str(audio_path),codec='pcm_s16le',write_logfile=True,verbose=True)#, codec='pcm_s16le')

            # Print a success message
            print(f"Audio extracted and saved as: {audio_path}")
        except Exception as e:
            print(f"Error converting MP4 to MP3: {e}")

    def download_mp4(video_url,oppath):
        # Get the YouTube object
        yt = YouTube(video_url)

        # Get video title and language
        title = yt.title
       # print (title)

        video_stream = yt.streams.filter(adaptive=True).order_by('abr')
       # print(video_stream)
        fname=sanitize_filepath(oppath/ f'{title}.mp4')
        video_stream.last().download(filename=oppath/ f'{title}.mp4')
        return fname

    filteroption={
        'resolution':'720p',
        'mp4':True,
        'audio':True,
        'adaptive':False,
    }

    songs=[
        'https://youtu.be/_HleLk2vTHY?si=eJsAXvUEkvhMwvlm',
        'https://youtu.be/-hVB1Lv32dE?si=JAEptI4wSZ7sNHI4',
        'https://youtu.be/RJQks-JWOXE?si=NJUYWipKfunf7-KI',
        'https://youtu.be/YDxS20SsyHg?si=zDLn5_UlAMrU1vhA',
        'https://youtu.be/srY3Y6r1-VY?si=nAPubWmZWiq7hjq1',
        'https://youtu.be/BhUxb0henfw?si=kCR5dIuyxaMT2GD1'
        'https://youtu.be/EAmqmSkOE68?si=KfamPtR2c4maXpQP',
        'https://youtu.be/RK1V6T5YNpI?si=vuWocaC12es68raT',
        'https://youtu.be/o9sS9y0UWZY?si=N_MVwMewolkYLlhN',
        'https://youtu.be/1ewcPZ8-nX8?si=reKig_CIB7NBy-do',
        'https://youtu.be/EIadKxo1ZBs?si=BcMX01vnYAJkjJYb',
        'https://youtu.be/2zencBD3z68?si=dayfVeYawB-egqxP',
        'https://youtu.be/drFWZ1-NQmE?si=cCoh3Is_nObNvOK5',
        'https://youtu.be/NpIIwVj1ZFU?si=La7ump84_1O61sDT',
        'https://youtu.be/iSF26HsmeRI?si=RAl9v4-a7qAQKD39'
    ]

    songs_090324=[
        'https://www.youtube.com/watch?v=cce9JqwPFkY',
        'https://www.youtube.com/watch?v=I9Wqm1W5-4s',
        'https://www.youtube.com/watch?v=ZW2xa__89p0',
        'https://www.youtube.com/watch?v=fFjUyhd0zz4',
        'https://www.youtube.com/watch?v=QXzC2eiHBG8',
        'https://www.youtube.com/watch?v=L6fmdfQK3es',
        'https://www.youtube.com/watch?v=9auVFKjZS7c',
        'https://www.youtube.com/watch?v=PJo8F-L0HMs',
        'https://www.youtube.com/watch?v=I6nqiTIKdL4',
        'https://www.youtube.com/watch?v=TADxdahPBUA',
        'https://www.youtube.com/watch?v=lrIKt5uDWZo'
    ]

    songs_250324=[
        'https://www.youtube.com/watch?v=UYCg6NBiXMI',
        'https://www.youtube.com/watch?v=p9XrgGAafhc',
        'https://www.youtube.com/watch?v=x5Oag4hISgU',
        'https://www.youtube.com/watch?v=tHyHOUShOg8&t=16s',
        'https://www.youtube.com/watch?v=S-u6qdeaPoE&t=229s',
        'https://www.youtube.com/watch?v=9_qij2b9-Jg',
        'https://www.youtube.com/watch?v=I9Wqm1W5-4s',
        'https://www.youtube.com/watch?v=0SVaz8VWE84',
        'https://www.youtube.com/watch?v=s7-GTShjcqY'
    ]

    songs_180424=[
        'https://www.youtube.com/watch?v=5ng1ypdkRIc',
        'https://www.youtube.com/watch?v=TgBww5kmgmg',
        'https://www.youtube.com/watch?v=t9wCMPCgeCk',
        'https://www.youtube.com/watch?v=rpP2JjFKthU',
        'https://www.youtube.com/watch?v=-H4umqfVoHk'
    ]

    playlist=[
        'https://www.youtube.com/watch?v=rknrt3tykH8&list=PL89GLpYyckZgglcqylKKyEdoUZ17drYAf&index=2'

    ]
    def download_songlist(songs):
        oppath=Path('/home/ys/Music/Miri/5_playlist')
        for song in songs:
            try:
                file=download_mp4(song,oppath)
                convert_mp4_to_mp3(file,oppath)
            except Exception as e:
                print(f"Error converting MP4 to MP3: {e}")
                continue

    download_songlist(songs_250324)

    audio_path Shawn Mendes - Stitches (Lyrics) /home/ys/Music/Miri/5_playlist/mp3/Shawn Mendes - Stitches (Lyrics).mp3
    MoviePy - Writing audio in /home/ys/Music/Miri/5_playlist/mp3/Shawn Mendes - Stitches (Lyrics).mp3

    MoviePy - Done.
    Audio extracted and saved as: /home/ys/Music/Miri/5_playlist/mp3/Shawn Mendes - Stitches (Lyrics).mp3
    audio_path DARKSIDE /home/ys/Music/Miri/5_playlist/mp3/DARKSIDE.mp3
    MoviePy - Writing audio in /home/ys/Music/Miri/5_playlist/mp3/DARKSIDE.mp3

    MoviePy - Done.
    Audio extracted and saved as: /home/ys/Music/Miri/5_playlist/mp3/DARKSIDE.mp3
    audio_path Rasputin /home/ys/Music/Miri/5_playlist/mp3/Rasputin.mp3
    MoviePy - Writing audio in /home/ys/Music/Miri/5_playlist/mp3/Rasputin.mp3

    MoviePy - Done.
    Audio extracted and saved as: /home/ys/Music/Miri/5_playlist/mp3/Rasputin.mp3
    audio_path Boney M - Daddy Cool (Original video) 1976 /home/ys/Music/Miri/5_playlist/mp3/Boney M - Daddy Cool (Original video) 1976.mp3
    MoviePy - Writing audio in /home/ys/Music/Miri/5_playlist/mp3/Boney M - Daddy Cool (Original video) 1976.mp3

    MoviePy - Done.
    Audio extracted and saved as: /home/ys/Music/Miri/5_playlist/mp3/Boney M - Daddy Cool (Original video) 1976.mp3
    audio_path Boney M. - Sunny (Official Video) [HD 1080p] /home/ys/Music/Miri/5_playlist/mp3/Boney M. - Sunny (Official Video) [HD 1080p].mp3
    MoviePy - Writing audio in /home/ys/Music/Miri/5_playlist/mp3/Boney M. - Sunny (Official Video) [HD 1080p].mp3

    MoviePy - Done.
    Audio extracted and saved as: /home/ys/Music/Miri/5_playlist/mp3/Boney M. - Sunny (Official Video) [HD 1080p].mp3
    Error converting MP4 to MP3: MoviePy error: the file /home/ys/Music/Miri/5_playlist/Charles & Eddie - Would I lie to you baby (Lyrics)  BUGG Lyrics.mp4 could not be found!
    Please check that you entered the correct path.
    audio_path You /home/ys/Music/Miri/5_playlist/mp3/You.mp3
    MoviePy - Writing audio in /home/ys/Music/Miri/5_playlist/mp3/You.mp3

    MoviePy - Done.
    Audio extracted and saved as: /home/ys/Music/Miri/5_playlist/mp3/You.mp3
    audio_path People You Know (Official Lyrics) /home/ys/Music/Miri/5_playlist/mp3/People You Know (Official Lyrics).mp3
    MoviePy - Writing audio in /home/ys/Music/Miri/5_playlist/mp3/People You Know (Official Lyrics).mp3

    MoviePy - Done.
    Audio extracted and saved as: /home/ys/Music/Miri/5_playlist/mp3/People You Know (Official Lyrics).mp3
    audio_path DARKSIDE /home/ys/Music/Miri/5_playlist/mp3/DARKSIDE.mp3
    MoviePy - Writing audio in /home/ys/Music/Miri/5_playlist/mp3/DARKSIDE.mp3

    MoviePy - Done.
    Audio extracted and saved as: /home/ys/Music/Miri/5_playlist/mp3/DARKSIDE.mp3

https://www.fatpick.com/blog?in=music-theory

image.png

    #for i in range(40,88,1):
    #    guitar.play_note(i,1,0.2)

    Using preset Guitar Nylon X for guitar nylon

    NOTES_FLAT = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B']
    NOTES_SHARP = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
    NOTES_FLAT=[str.lower(_) for _ in NOTES_FLAT]
    NOTES_SHARP=[str.lower(_) for _ in NOTES_SHARP]
    #def NoteToMidi_guitar(string, fret):
    import pandas as pd
    import numpy as np
    from itertools import product
    def NoteToMidi(KeyOctave):
        # KeyOctave is formatted like 'C#3'
        key = KeyOctave[:-1]  # eg C, Db
        octave = KeyOctave[-1]   # eg 3, 4
        answer = -1

        try:
            if 'b' in key:
                pos = NOTES_FLAT.index(key)
            else:
                pos = NOTES_SHARP.index(key)
        except:
            print('The key is not valid', key)
            return answer

        answer += pos + 12 * (int(octave) + 1) + 1
        return answer

    def guitarToMidi(string,fret):
        openstr={}
        openstr[6]=40
        openstr[5]=45
        openstr[4]=50
        openstr[3]=55
        openstr[2]=59
        openstr[1]=64
        midi=openstr[string]+fret
        notes=miditoGuitarNote_sharps.loc[midi,0]
        notef=miditoGuitarNote_flats.loc[midi,0]
        return midi,notes,notef

    miditoGuitarNote_sharps=(pd.concat([pd.Series({NoteToMidi(f'{k}{o}'):f'{k}{o}' for o,k in product(range(0,7,1),NOTES_SHARP)}),
        ], axis=1
        )
        .assign(E=lambda df: np.where((df.index>=40) & (df.index<59),df[0],0),
                A=lambda df: np.where((df.index>=45) & (df.index<64),df[0],0),
                D=lambda df: np.where((df.index>=50) & (df.index<69),df[0],0),
                G=lambda df: np.where((df.index>=55) & (df.index<74),df[0],0),
                B=lambda df: np.where((df.index>=59) & (df.index<78),df[0],0),
                e=lambda df: np.where((df.index>=64) & (df.index<83),df[0],0),
                )
    )

    miditoGuitarNote_flats=(pd.concat([pd.Series({NoteToMidi(f'{k}{o}'):f'{k}{o}' for o,k in product(range(0,7,1),NOTES_FLAT)}),
        ], axis=1
        )
        .assign(E=lambda df: np.where((df.index>=40) & (df.index<59),df[0],0),
                A=lambda df: np.where((df.index>=45) & (df.index<64),df[0],0),
                D=lambda df: np.where((df.index>=50) & (df.index<69),df[0],0),
                G=lambda df: np.where((df.index>=55) & (df.index<74),df[0],0),
                B=lambda df: np.where((df.index>=59) & (df.index<78),df[0],0),
                e=lambda df: np.where((df.index>=64) & (df.index<83),df[0],0),
                )
    )

    #guitarToMidi(6,2)[0]

    from scamp import *

    s= Session() # (temp=100,)
    #s.print_default_soundfont_presets()
    guitar=s.new_part("guitar nylon")

    #https://www.fatpick.com/blog/note-table
    #http://scamp.marcevanstein.com/narrative/tutorial_videos.html

    #
    count=0
    vol=0
    #guitar.play_note(guitarToMidi(6,0)[0],1,5,blocking=False)
    for string in reversed(range(1,7,1)):
        for fret in range(0,5):

            if (count%3==0):
                vol=1
            else:
                vol=0.7
            count+=1

            guitar.play_note(guitarToMidi(string,fret)[0],vol,0.1)
    #guitar.play_note(40,1,2)
    #guitar.play_note(83,1,2)
    #guitar.play_chord([70,73,83],1,2)
    #guitar.play_note(52,1,5)
    s.beat_length

    Using preset Guitar Nylon X for guitar nylon

    1.0

    import abjad
    string = "c'16 f' g' a' d' g' a' b' e' a' b' c'' f' b' c'' d''16"
    voice_1 = abjad.Voice(string, name="Voice_1")
    staff_1 = abjad.Staff([voice_1], name="Staff_1")
    abjad.show(staff_1)