Skip to content
Shrijayan
Go back

Speech-to-Text Toolkit

Speech-to-Text Toolkit

Download original notebook: [Speech-to-Text Toolkit.ipynb](/notebooks/Speech-to-Text Toolkit.ipynb)

Speech-to-Text Toolkit

Combined notebook — sections below are preserved verbatim from their originals.

Copy of stt

Merged from Copy of stt.ipynb (2021-12-01)

pip install SpeechRecognition pydub
# importing libraries 
import speech_recognition as sr 
import os 
from pydub import AudioSegment
from pydub.silence import split_on_silence

# create a speech recognition object
r = sr.Recognizer()

# a function that splits the audio file into chunks
# and applies speech recognition
def get_large_audio_transcription(path):
    """
    Splitting the large audio file into chunks
    and apply speech recognition on each of these chunks
    """
    # open the audio file using pydub
    sound = AudioSegment.from_wav(path)  
    # split audio sound where silence is 700 miliseconds or more and get chunks
    chunks = split_on_silence(sound,
        # experiment with this value for your target audio file
        min_silence_len = 500,
        # adjust this per requirement
        silence_thresh = sound.dBFS-14,
        # keep the silence for 1 second, adjustable as well
        keep_silence=500,
    )
    folder_name = "audio-chunks"
    # create a directory to store the audio chunks
    if not os.path.isdir(folder_name):
        os.mkdir(folder_name)
    whole_text = ""
    # process each chunk 
    for i, audio_chunk in enumerate(chunks, start=1):
        # export audio chunk and save it in
        # the `folder_name` directory.
        chunk_filename = os.path.join(folder_name, f"chunk{i}.wav")
        audio_chunk.export(chunk_filename, format="wav")
        # recognize the chunk
        with sr.AudioFile(chunk_filename) as source:
            audio_listened = r.record(source)
            # try converting it to text
            try:
                text = r.recognize_google(audio_listened)
            except sr.UnknownValueError as e:
                print("Error:", str(e))
            else:
                text = f"{text.capitalize()}. "
                print(chunk_filename, ":", text)
                whole_text += text
    # return the text for all chunks detected
    return whole_text
path = "/content/sampe.audio.wav"
print("\nFull text:", get_large_audio_transcription(path))
file = open("testfile.txt","w+")
file.write(get_large_audio_transcription(path))
file.close()
from gramformer import Gramformer
import torch

def set_seed(seed):
  torch.manual_seed(seed)
  if torch.cuda.is_available():
    torch.cuda.manual_seed_all(seed)

set_seed(1212)


gf = Gramformer(models = 2, use_gpu=False) # 0=detector, 1=highlighter, 2=corrector, 3=all 

influent_sentences = ["content/testfile.txt"]   

for influent_sentence in influent_sentences:
    corrected_sentence = gf.correct(influent_sentence)
    print("[Input] ", influent_sentence)
    print("[Correction] ",corrected_sentence[0])
    print("-" *100)
import filecmp
d1 = "content/testfile.txt"
d2 = "content/final.txt"
files = ['intro.txt']
  
# shallow comparison
match, mismatch, errors = filecmp.cmpfiles(d1, d2, files)
print('Shallow comparison')
print("Match:", match)
print("Mismatch:", mismatch)
print("Errors:", errors)
  
# deep comparison
match, mismatch, errors = filecmp.cmpfiles(d1, d2, files, shallow=False)
print('Deep comparison')
print("Match:", match)
print("Mismatch:", mismatch)
print("Errors:", errors)

Untitled5

Merged from Untitled5.ipynb (2021-12-21)

New Section

pip install azure-cognitiveservices-speech
!pip install --upgrade pip
import azure.cognitiveservices.speech as speechsdk
import azure.cognitiveservices.speech as speechsdk

def from_mic():
    speech_config = speechsdk.SpeechConfig(subscription="6.....9", region="centralindia")
    speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config)
    
    print("Speak into your microphone.")
    result = speech_recognizer.recognize_once_async().get()
    print(result.text)

from_mic()

New Section

pip install SpeechRecognition

import speech_recognition as spr
spr.__version__
recog = spr.Recognizer()
recog.recognize_google()
mc = spr.Microphone()
#sr.Microphone.list_microphone_names()
mc.list_microphone_names()
mc = spr.Microphone(device_index=0)
with mc as source:
    audio = recog.listen(source)
recog.recognize_google(audio)
#Reducing the effect of Noise
with mc as source:
    recog.adjust_for_ambient_noise(source)
    audio = recog.listen(source)

Share this post on:

Next Post
Vector Databases: A Survey of the Landscape