Home > Blockchain >  Python for/while loop
Python for/while loop

Time:09-17

Today i am working on a project about incoming phone calls being transcripted and getting saved into text files, but i am also kinda new to python and python loops. I want to loop over a SQL server column and let each row loop trough the azure Speech to text service i use (all of the phonecall OID's). I have been stuck on this problem for a couple days now so i thought i might find some help here.

import azure.cognitiveservices.speech as speechsdk
import time
from os import path
from pydub import AudioSegment
import requests
import hashlib
import sys
import os.path
import pyodbc

databaseName = '*'
username = '*'
password = '*'
server = '*'
driver = '*'

try:
    CONNECTION_STRING = 'DRIVER=' driver ';SERVER=' server ';DATABASE=' databaseName ';UID=' username ';PWD='  password

    conn = pyodbc.connect(CONNECTION_STRING)

    cursor = conn.cursor()
    storedproc = "* = *'"
    cursor.execute(storedproc)
    row = cursor.fetchone()
    while row:
        array = [(int(row[1]))]
        row = cursor.fetchone()

        i = 0
        while i<len(array):
            OID = (array[i])
            i = i   1
            print(OID)


        string = f"{OID}*"
        encoded = string.encode()
        result = hashlib.sha256(encoded)
        resultHash = (result.hexdigest())

        Telefoongesprek = requests.get(f"*{OID}", headers={f"api-key":f"{resultHash}"})



        with open("Telefoongesprek.mp3", "wb") as f:
            f.write(Telefoongesprek.content)

        src = "Telefoongesprek.mp3"
        dst = "Telefoongesprek.wav"

        sound = AudioSegment.from_file(src)
        sound.export(dst, format="wav")


        def speech_recognize_continuous_from_file():
            speech_config = speechsdk.SpeechConfig(subscription="*", region="*")
            speech_config.speech_recognition_language = "nl-NL"
            audio_config = speechsdk.audio.AudioConfig(filename="Telefoongesprek.wav")

            speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)

            done = False

            def stop_cb(evt):
                print('CLOSING on {}'.format(evt))
                nonlocal done
                done = True

            all_results = []
            def handle_final_result(evt):
                all_results.append(evt.result.text)
            speech_recognizer.recognized.connect(handle_final_result)
            speech_recognizer.session_started.connect(handle_final_result)
            speech_recognizer.session_stopped.connect(handle_final_result)
            speech_recognizer.canceled.connect(handle_final_result)
            speech_recognizer.session_stopped.connect(stop_cb)
            speech_recognizer.canceled.connect(stop_cb)

            speech_recognizer.start_continuous_recognition()
            while not done:
                time.sleep(.5)

            speech_recognizer.stop_continuous_recognition()

            print(all_results)

            telefoongesprek = str(all_results)
            filename = f"C:\\Users\\Beau\\Contact-verkeer\\contact-verkeer\\telefoon\\STT Transcriptions\\Telefoongesprek#{OID}.txt"
            file = open(filename, "w")
            file.write(telefoongesprek)
            file.close()


        speech_recognize_continuous_from_file()
        cursor.close()
        del cursor

        conn.close()

except Exception as e:
    print("Error: %s" % e)

everything works apart form each other but i just dont know how to place the loop and witch one i should use (For/While loop). right here im trying to loop over an array but i dont this this is correct.

Error message: Decoding failed. ffmpeg returned error code: 1 [mp3 @ 000001cb8c57e0o0] Failed to read frame size: could not seek to 1073.

which i am pretty sure means that my azure function can't find an mp3 file, what means that the "Mp3 to Wav" convert doesn't work.

Thanks in advance!

CodePudding user response:

If I understand your question, you have a database with lots of phone call details. One of the field value in each row is used to create the associated mp3 file. You want to do speech to text using azure on each of the mp3 file you have in your database.

So you can do it in two ways:

  1. Iterate though all rows in the database and create all the associted files into a folder in the local disk with the OID as your filename.
  2. Then write another loop to iterate through this folder and send the files for transcription to Azure Speech to Text service.

The other technique is to do everything in a single loop like the way you have shown which will require some corrections.

Ok, so now that part is clear, we can go into the speech to text part. So azure allow you to send the compressed format for transcription, which means you actually don't need to convert it into wav file.

Please have a look at the modified code below with the changes:

# code snippet borrowed from azure samples
def speech_recognize_continuous_from_file(filename):
    class BinaryFileReaderCallback(speechsdk.audio.PullAudioInputStreamCallback):
        def __init__(self, filename: str):
            super().__init__()
            self._file_h = open(filename, "rb")

        def read(self, buffer: memoryview) -> int:
            try:
                size = buffer.nbytes
                frames = self._file_h.read(size)

                buffer[:len(frames)] = frames

                return len(frames)
            except Exception as ex:
                print('Exception in `read`: {}'.format(ex))
                raise

        def close(self) -> None:
            print('closing file')
            try:
                self._file_h.close()
            except Exception as ex:
                print('Exception in `close`: {}'.format(ex))
                raise

    # Creates an audio stream format. For an example we are using MP3 compressed file here
    compressed_format = speechsdk.audio.AudioStreamFormat(compressed_stream_format=speechsdk.AudioStreamContainerFormat.MP3)
    callback = BinaryFileReaderCallback(filename=filename)

    stream = speechsdk.audio.PullAudioInputStream(stream_format=compressed_format, pull_stream_callback=callback)

    speech_config = speechsdk.SpeechConfig(subscription="*", region="*")
    speech_config.speech_recognition_language = "nl-NL"
    audio_config = speechsdk.audio.AudioConfig(stream=stream)

    # Creates a speech recognizer using a file as audio input, also specify the speech language
    speech_recognizer = speechsdk.SpeechRecognizer(speech_config, audio_config)

    done = False

    def stop_cb(evt):
        print('CLOSING on {}'.format(evt))
        nonlocal done
        done = True

    all_results = []

    def handle_final_result(evt):
        all_results.append(evt.result.text)

    speech_recognizer.recognized.connect(handle_final_result)
    speech_recognizer.session_started.connect(handle_final_result)
    speech_recognizer.session_stopped.connect(handle_final_result)
    speech_recognizer.canceled.connect(handle_final_result)
    speech_recognizer.session_stopped.connect(stop_cb)
    speech_recognizer.canceled.connect(stop_cb)

    speech_recognizer.start_continuous_recognition()
    while not done:
        time.sleep(.5)

    speech_recognizer.stop_continuous_recognition()

    print(all_results)

    telefoongesprek = str(all_results)
    filename = f"C:\\Users\\Beau\\Contact-verkeer\\contact-verkeer\\telefoon\\STT Transcriptions\\Telefoongesprek#{OID}.txt"
    file = open(filename, "w")
    file.write(telefoongesprek)
    file.close()

try:
    CONNECTION_STRING = 'DRIVER=' driver ';SERVER=' server ';DATABASE=' databaseName ';UID=' username ';PWD='  password

    conn = pyodbc.connect(CONNECTION_STRING)

    cursor = conn.cursor()
    storedproc = "* = *'"
    cursor.execute(storedproc)
    row = cursor.fetchone()
    # loop through the rows
    while row:
        array = [(int(row[1]))]

        i = 0
        while i<len(array):
            OID = (array[i])
            i = i   1
            print(OID)

        string = f"{OID}*"
        encoded = string.encode()
        result = hashlib.sha256(encoded)
        resultHash = (result.hexdigest())

        telefoongesprek_response = requests.get(f"*{OID}", headers={f"api-key":f"{resultHash}"})

        # save the file to local disk as mp3
        with open("Telefoongesprek.mp3", "wb") as f:
            f.write(telefoongesprek_response.content)

        # do the speech to text on the mp3 file
        speech_recognize_continuous_from_file(f.name)

        # fetch the next row
        row = cursor.fetchone()

    cursor.close()
    del cursor
    conn.close()
except Exception as e:
    print("Error: %s" % e)

I haven't tested this full code as i don't have the db connections with me. Please fell free to modify for your use case and let me know if you have any issues.

  • Related