Monday, March 11, 2024

Code that I run to manually control syllables instead of words transcription

 The code below

I would run it by setting syllables to something like ['XXXX']

Then you see the list of words printed out, there might be more than 1 segment depending how long your audio is.

Then copy the printed words all together and break them into your own syllables (manually) and then set syllables variable to that list and rerun the program so that it breaks it using your manually defined syllables.

Result video shown here: https://www.youtube.com/shorts/3EAT2BO8C_0

# here's the code ------------------

import torch

import torchaudio

from datetime import timedelta

from dataclasses import dataclass

from srt import Subtitle, compose

import whisper

from pydub import AudioSegment

import re

import num2words


device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

torch.cuda.empty_cache()

torch.random.manual_seed(0)

#HACK HERE INSTEAD

syllables = ['WHAT',

'HAP',

'PENS',

'IF',

'YOU',

'TAKE',

'SPEECH',

'AU',

'DIO',

'CLIP',

'GET',

'A',

'TIME',

'TRAN',

'SCRIPT',

'FOR',

'EACH',

'SYL',

'LA',

'BLE',

'NOT',

'WORDS',

'THEN',

'PLAY',

'A',

'MU',

'SI',

'CAL',

'NOTE',

'THAT',

'CLO',

'SEST',

'MATCH',

'EACH',

'SYL',

'LA',

'BLE',

'YOU',

'RE',

'LIS',

'TE',

'NING',

'TO',

'THE',

'RE',

'SULT',

'RIGHT',

'NOW']

syllablei = 0    


def force_align(SPEECH_FILE, transcript, start_index, start_time):

    global syllables,syllablei

    bundle = torchaudio.pipelines.WAV2VEC2_ASR_BASE_960H

    model = bundle.get_model().to(device)

    labels = bundle.get_labels()

    with torch.inference_mode():

        waveform, _ = torchaudio.load(SPEECH_FILE)

        emissions, _ = model(waveform.to(device))

        emissions = torch.log_softmax(emissions, dim=-1)


    emission = emissions[0].cpu().detach()


    dictionary = {c: i for i, c in enumerate(labels)}


    default_token = 0;#default_token = 'A';

    #tokens = [dictionary[c] for c in transcript]

    tokens = [dictionary.get(c, default_token) for c in transcript]


    def get_trellis(emission, tokens, blank_id=0):

        num_frame = emission.size(0)

        num_tokens = len(tokens)


        # Trellis has extra diemsions for both time axis and tokens.

        # The extra dim for tokens represents <SoS> (start-of-sentence)

        # The extra dim for time axis is for simplification of the code.

        trellis = torch.empty((num_frame + 1, num_tokens + 1))

        trellis[0, 0] = 0

        trellis[1:, 0] = torch.cumsum(emission[:, 0], 0)

        trellis[0, -num_tokens:] = -float("inf")

        trellis[-num_tokens:, 0] = float("inf")


        for t in range(num_frame):

            trellis[t + 1, 1:] = torch.maximum(

                # Score for staying at the same token

                trellis[t, 1:] + emission[t, blank_id],

                # Score for changing to the next token

                trellis[t, :-1] + emission[t, tokens],

            )

        return trellis



    trellis = get_trellis(emission, tokens)


    @dataclass

    class Point:

        token_index: int

        time_index: int

        score: float



    def backtrack(trellis, emission, tokens, blank_id=0):

        # Note:

        # j and t are indices for trellis, which has extra dimensions

        # for time and tokens at the beginning.

        # When referring to time frame index `T` in trellis,

        # the corresponding index in emission is `T-1`.

        # Similarly, when referring to token index `J` in trellis,

        # the corresponding index in transcript is `J-1`.

        j = trellis.size(1) - 1

        t_start = torch.argmax(trellis[:, j]).item()


        path = []

        for t in range(t_start, 0, -1):

            # 1. Figure out if the current position was stay or change

            # Note (again):

            # `emission[J-1]` is the emission at time frame `J` of trellis dimension.

            # Score for token staying the same from time frame J-1 to T.

            stayed = trellis[t - 1, j] + emission[t - 1, blank_id]

            # Score for token changing from C-1 at T-1 to J at T.

            changed = trellis[t - 1, j - 1] + emission[t - 1, tokens[j - 1]]


            # 2. Store the path with frame-wise probability.

            prob = emission[t - 1, tokens[j - 1] if changed > stayed else 0].exp().item()

            # Return token index and time index in non-trellis coordinate.

            path.append(Point(j - 1, t - 1, prob))


            # 3. Update the token

            if changed > stayed:

                j -= 1

                if j == 0:

                    break

        else:

            raise ValueError("Failed to align")

        return path[::-1]



    path = backtrack(trellis, emission, tokens)


    # Merge the labels

    @dataclass

    class Segment:

        label: str

        start: int

        end: int

        score: float


        def __repr__(self):

            return f"{self.label}\t({self.score:4.2f}): [{self.start:5d}, {self.end:5d})"


        @property

        def length(self):

            return self.end - self.start



    def merge_repeats(path):

        i1, i2 = 0, 0

        segments = []

        while i1 < len(path):

            while i2 < len(path) and path[i1].token_index == path[i2].token_index:

                i2 += 1

            score = sum(path[k].score for k in range(i1, i2)) / (i2 - i1)

            segments.append(

                Segment(

                    transcript[path[i1].token_index],

                    path[i1].time_index,

                    path[i2 - 1].time_index + 1,

                    score,

                )

            )

            i1 = i2

        return segments



    segments = merge_repeats(path)


    # HACK HERE TO GET MANUAL SYLLABLES

    


    # Merge words

    def merge_words(segments, separator="|"):

        global syllables,syllablei

        words = []

        i1, i2 = 0, 0

        

        while i1 < len(segments):

            #HACK CODE HERE ---------

            segs = segments[i1:i2]

            syllable = "".join([seg.label for seg in segs])


            if i2 >= len(segments) or segments[i2].label == separator or syllable == syllables[syllablei]: #HACK PART syllable == syllables[syllablei]:

                


                if i1 != i2:

                    segs = segments[i1:i2]

                    word = "".join([seg.label for seg in segs])

                    print("'"+word+"'");

                    score = sum(seg.score * seg.length for seg in segs) / sum(seg.length for seg in segs)

                    if i2 < len(segments) and segments[i2].label != separator: #HACK IF NOT SEPARATOR WE DON"T INCREMENT BY 1

                        words.append(Segment(word, segments[i1].start, segments[i2].end, score))

                    else:

                        words.append(Segment(word, segments[i1].start, segments[i2 - 1].end, score))


                if i2 < len(segments) and segments[i2].label != separator: #HACK IF NOT SEPARATOR WE DON"T INCREMENT BY 1

                    i1 = i2

                    i2 = i1

                else:    

                    i1 = i2 + 1

                    i2 = i1

                if syllablei < len(syllables)-1:

                    syllablei+=1

            else:

                i2 += 1

        return words


    word_segments = merge_words(segments)

    subs = []

    last_end = timedelta(seconds=start_time/bundle.sample_rate)

    for i,word in enumerate(word_segments):

        ratio = waveform.size(1) / (trellis.size(0) - 1)

        x0 = int(ratio * word.start)

        x1 = int(ratio * word.end)

        

        start = max(timedelta(seconds=start_time + x0 / bundle.sample_rate),last_end)

        end = timedelta(seconds=start_time + x1 / bundle.sample_rate )

        last_end = start

        subtitle = Subtitle(start_index+i, start, end, word.label)

        subs.append(subtitle)


    print(compose(subs))

    return subs



model = whisper.load_model("medium")


audio = whisper.load_audio("video.wav")


transcription = model.transcribe(audio)

# # print the recognized text

segments = transcription["segments"]

print("Transcription complete:")

print(transcription["text"])

print("Starting to force alignment...")

start_index = 0

total_subs = []

for i,segment in enumerate(segments):

    text = segment["text"]

    audioSegment = AudioSegment.from_wav("video.wav")[segment["start"]*1000:segment["end"]*1000]

    audioSegment.export(str(i)+'.wav', format="wav") #Exports to a wav file in the current path.

    transcript=text.strip().replace(" ", "|")

    transcript = re.sub(r'[^\w|\s]', '', transcript)

    transcript = re.sub(r"(\d+)", lambda x: num2words.num2words(int(x.group(0))), transcript)

    print(segment["start"])

    subs = force_align(str(i)+'.wav', transcript.upper(), start_index, segment["start"])

    start_index += len(segment["text"])

    total_subs.extend(subs)

CAPTION_FILE = open("caption.srt", "w", encoding="utf-8") #open("caption.srt", "w")

CAPTION_FILE.write(compose(total_subs))

CAPTION_FILE.close()


Sunday, March 10, 2024

Sharing code I used to match musical notes to speech

Demo or result of this code can be seen in this youtube video

#------------- video description ------------------------------

SPEECH: "What happens if you take speech audio clip, Get a timed transcript for words, Then play a musical note that closest match each word." - by https://elevenlabs.io/ 1. Recorded using Audacity, exported to "video.wav" at 16000 Hz. 2. Put in same folder as generate.py Python file found on https://github.com/johnafish/whisperer Had a problem running python generate.py but fixed it with this answer: https://github.com/openai/whisper/discussions/120 3. It'll generate caption.srt file in the same folder 4. Then you can get code which I prompted chatGPT to help me with to turn the "caption.srt" along with original "video.wav" to another .wav file which you can then use Audacity to play along/export together like shown in video. (code shown below) Hope you like this. Let me know in comments what you do with it love to see more related to this.



# -------------------------------------------------------------------------------------------------------------------

#---- code starts -------------- This code was mostly by ChatGPT

# I just changed configuration details such as note frequencies and folder path to point

# to to get my mp3 for sounds to use

import pysrt

from pydub import AudioSegment

from pydub.generators import Sine

import librosa

import numpy as np

#from pydub import AudioSegment

#import pysrt

#import librosa

#import numpy as np


# Load the SRT file

subs = pysrt.open('caption.srt')


# Load the WAV file

audio = AudioSegment.from_wav('video.wav')

note_frequencies = {

    'C3': 130.81,

    'D3': 146.83,

    'E3': 164.81,

    'F3': 174.61,

    'G3': 196.00,

    'A3': 220.00,

    'B3': 246.94,

    'C4': 261.63,

    'D4': 293.66,

    'E4': 329.63,

    'F4': 349.23,

    'G4': 392.00,

    'A4': 440.00,

    'B4': 493.88,

    'C5': 523.25,

    'D5': 587.33,

    'E5': 659.25,

    'F5': 698.46,

    'G5': 783.99,

    'A5': 880.00,

    'B5': 987.77,

}

flute_sounds = {note: AudioSegment.from_mp3(f'../songs/{note}.mp3') for note in note_frequencies}

# Function to extract pitch using librosa

def find_closest_note(pitch):

    # Find the closest note for the given pitch

    closest_note = min(note_frequencies.keys(), key=lambda note: abs(note_frequencies[note] - pitch))

    return closest_note

def extract_pitch(audio_segment, sr=16000, n_fft=2048, hop_length=512, fmin=75, fmax=1500):

    samples = np.array(audio_segment.get_array_of_samples())

    float_samples = librosa.util.buf_to_float(samples, n_bytes=2, dtype=np.float32)

    

    pitches, magnitudes = librosa.piptrack(y=float_samples, sr=sr, n_fft=n_fft, hop_length=hop_length, fmin=fmin, fmax=fmax)

    pitches = pitches[magnitudes > np.median(magnitudes)]

    if len(pitches) == 0:

        return 0

    return np.mean(pitches)

def extract_pitch2(audio_segment, sr=16000):

    # Convert PyDub audio segment to NumPy array

    samples = np.array(audio_segment.get_array_of_samples())

    float_samples = librosa.util.buf_to_float(samples, n_bytes=2, dtype=np.float32)

    

    # Extract pitch

    pitches, magnitudes = librosa.piptrack(y=float_samples, sr=sr)

    pitches = pitches[magnitudes > np.median(magnitudes)]

    if len(pitches) == 0:

        return 0

    return np.mean(pitches)


# Create a new audio segment for the output

output_audio = AudioSegment.silent(duration=len(audio))


for i, sub in enumerate(subs):

    start_time = (sub.start.hours * 3600 + sub.start.minutes * 60 + sub.start.seconds) * 1000 + sub.start.milliseconds

    end_time = (sub.end.hours * 3600 + sub.end.minutes * 60 + sub.end.seconds) * 1000 + sub.end.milliseconds


    # Ensure the note does not overlap with the next word

    if i < len(subs) - 1:

        next_start_time = (subs[i + 1].start.hours * 3600 + subs[i + 1].start.minutes * 60 + subs[i + 1].start.seconds) * 1000 + subs[i + 1].start.milliseconds

        max_duration = min(end_time, next_start_time) - start_time

    else:

        max_duration = end_time - start_time


    word_audio = audio[start_time:end_time]

    pitch = extract_pitch(word_audio)

    if pitch > 0:

        closest_note = find_closest_note(pitch)

        note_audio = flute_sounds[closest_note]

        

        # Adjust the duration of the note

        if len(note_audio) > max_duration:

            note_audio = note_audio[:max_duration]

        

        output_audio = output_audio.overlay(note_audio, position=start_time)


# Export the output audio

output_audio.export("output_with_flute.wav", format="wav")
#----- code ends -------------

Friday, March 8, 2024

Endless Piano,Flute,Snare,QuietSnare,KickDrum Music Generator

Image Upload Demo

Thursday, March 7, 2024

Views/Likes Counter/Animator

View/Likes Counter/Animator

Starting Number:
Ending Number:
Number Font Size (pixels):
Unit Name (ie. Likes):
Unit Font Size (pixels):
Increment each step by:(Can be float/real number, numbers will still be shown in whole numbers)
Minimum Delay between counts (ms):
Maximum Delay between counts (ms):
Thousands Separator:
Background Color (HEX):
Font Color (HEX):
Unit Color (HEX):

Flute & Piano & Drums


Falling Leaves - Improvement by sampling pixels from image of fall leaves colors

Share code here

------------ code starts here --------------
<canvas id='canvas' width=1200 height=800 style='border:1px solid black'></canvas>
<!-- <img src='https://images.unsplash.com/photo-1523712999610-f77fbcfc3843?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D' id='img'> -->
<img src='https://i.imgur.com/3WN5wPL.jpeg' id='leafsample'>
<script>
leafsample = document.getElementById('leafsample');
img = document.getElementById('img');
colors = ['#82310d','#ffb614','#de7406','#7b1200']; //random colors from this

leaves = 1000;
wind = .03;
canvas = document.getElementById('canvas')
ctx = canvas.getContext("2d");
function clearscreen(){
    ctx.fillStyle = 'black';
ctx.fillRect(0,0,canvas.width,canvas.height);
}
clearscreen();
sample = [];
size = [];
color = [];
x = [];
y = [];
incx = [];
incy = [];
horizontalradius = [];
verticalradius = [];
horizontalangle = [];
horizontalangleinc = [];
verticalangle = [];
verticalangleinc = [];
for (var i=0;i<leaves;i++){
sample.push(Math.floor(Math.random()*(leafsample.height-5))); //get sample pixel area
size.push(Math.random()*1.5+0.5);
color.push(colors[Math.floor(Math.random()*colors.length)]);
x.push(Math.random()*canvas.width);
y.push(Math.random()*100);
incx.push(0);
incy.push(0);
horizontalradius.push(Math.random()*10+120);
verticalradius.push(Math.random()*20+10);
horizontalangle.push(Math.random()*Math.PI*2.0);//cos
horizontalangleinc.push(5/360.0*Math.PI*2.0);
verticalangle.push(-90/360*Math.PI*2.0); //start from top and drop down /// use sin
verticalangleinc.push(10/360.0*Math.PI*2.0);
}
function reset(i){
sample[i] = (Math.floor(Math.random()*(leafsample.height-5))); //get sample pixel area
x[i]=(Math.random()*canvas.width*3-canvas.width/2);
y[i]=(-Math.random()*100);
incx[i]=(0);
incy[i]=(0);
horizontalradius[i]=(Math.random()*120+30);
verticalradius[i]=(Math.random()*20+10);
horizontalangle[i]=(Math.random()*Math.PI*2.0);//cos
horizontalangleinc[i]=(5/360.0*Math.PI*2.0);
verticalangle[i]=(-90/360*Math.PI*2.0); //start from top and drop down /// use sin
verticalangleinc[i]=(10/360.0*Math.PI*2.0);
}
function updatestart(){
for (var i=0;i<leaves;i++){
r = Math.random()*1000;
for (var j;j<r;j++){
horizontalangle[i] = (horizontalangle[i]+horizontalangleinc[i])%(Math.PI*2.0);
verticalangle[i] = (verticalangle[i]+verticalangleinc[i])%(Math.PI*2.0);
y[i] +=incy[i];
incy[i] +=0.02;//due to gravity;

x[i]+=incx[i];
incx[i] += wind; //due to wind;
horizontalradius[i] -= 0.1;
}
x[i] = Math.random()*canvas.width;
y[i] = Math.random()*canvas.height;
// y[i] +=incy[i];
// incy[i] +=0.02;//due to gravity;

// x[i]+=incx[i];
// incx[i] += wind; //due to wind;
// horizontalradius[i] -= 0.1;
}
}
updatestart();
function update(){
for (var i=0;i<leaves;i++){
horizontalangle[i] = (horizontalangle[i]+horizontalangleinc[i])%(Math.PI*2.0);
verticalangle[i] = (verticalangle[i]+verticalangleinc[i])%(Math.PI*2.0);
y[i] +=incy[i]*size[i];
incy[i] +=0.05;//due to gravity;

x[i]+=incx[i]*size[i];
incx[i] += wind; //due to wind;
horizontalradius[i] -= 0.1;
}
}
function draw(){
clearscreen();
//ctx.drawImage(img,0,0,1200,800);
// ctx.fillStyle = 'black';
// ctx.fillRect(0,0,canvas.width,canvas.height);
for (var i=0;i<leaves;i++){
dx = x[i] + Math.cos(horizontalangle[i])*horizontalradius[i];
dy = y[i] + Math.sin(verticalangle[i])*verticalradius[i];
if (dy > canvas.height){
reset(i);
}
ctx.drawImage(leafsample,0,sample[i],leafsample.width,leafsample.width,dx-5,dy+3*size[i]*Math.sin(verticalangle[i]/2),20*size[i],Math.max(1,4*size[i]*Math.sin(verticalangle[i]/2)));
ctx.drawImage(leafsample,0,sample[i],leafsample.width,leafsample.width,dx,dy,10*size[i],Math.max(1,10*size[i]*Math.sin(verticalangle[i]/2)));
//ctx.fillStyle = color[i];
// ctx.fillRect(dx-5,dy+3*size[i]*Math.sin(verticalangle[i]/2),20*size[i],Math.max(1,4*size[i]*Math.sin(verticalangle[i]/2)));
// ctx.fillRect(dx,dy,10*size[i],Math.max(1,10*size[i]*Math.sin(verticalangle[i]/2)));
}
update();
}
setInterval(draw,30);
</script>
------------ code ends here ---------------

How to use the Color Picker

 Depending on the Color Picker, there will be minor differences (there are already step by step Instructions). But this is graphical Instruc...