File size: 4,125 Bytes
0429034
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""

Data Scientist.: Dr.Eddy Giusepe Chirinos Isidro



Speech-to-Text

==============

Este script (main.py) Grava sua fala e depois a transcreve.

Para Gravar pressiono 'r' e 'q' para terminar a gravação e 

juntar os trechos de áudios.



OBS: Eu só consegui executar este script como usuário root devido à biblioteca keyboard. ---> ImportError: You must be root to use this library on linux.

====



Link de estudo:



* https://platform.openai.com/docs/guides/speech-to-text

"""
import pyaudio
import openai
import wave
import keyboard
import os


# Substitua sua chave de API OpenAI:
import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key  = os.environ['OPENAI_API_KEY']


# Configurar parâmetros de gravação de áudio:
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 5

# Inicializar PyAudio:
audio = pyaudio.PyAudio()

# Iniciar contador de gravação:
recording_counter = 1

# Definir função de retorno de chamada (callback) para lidar com stream de áudio:
def callback(in_data, frame_count, time_info, status):
    """

    The callback function to handle the audio stream.



    :parâmetro in_data: dados de áudio.

    :parâmetro frame_count: O número de Frames.

    :parâmetro time_info: a dictionary of time information.

    :parâmetro status: the status of the stream.

    :return: a tuple of the audio data and a flag to indicate whether to continue the stream.

    """
    frames.append(in_data)
    return (in_data, pyaudio.paContinue)

# criar ouvinte de evento de teclado:
def on_press(event):
    """

    The function to handle the keyboard events.



    :param event: the keyboard event.

    """
    global recording, frames, stream, WAVE_OUTPUT_FILENAME, recording_counter
    if event.name == 'r':
        if not recording:
            # Iniciar a Gravação:
            recording = True
            frames = []

            WAVE_OUTPUT_FILENAME = f"output_{recording_counter}.wav"
            recording_counter += 1

            stream = audio.open(format=FORMAT, channels=CHANNELS,
                                rate=RATE, input=True,
                                frames_per_buffer=CHUNK,
                                stream_callback=callback)
            stream.start_stream()

            print("A gravação começou")
        else:
            # pare de gravar e salve o arquivo de áudio:
            recording = False
            stream.stop_stream()
            stream.close()

            waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
            waveFile.setnchannels(CHANNELS)
            waveFile.setsampwidth(audio.get_sample_size(FORMAT))
            waveFile.setframerate(RATE)
            waveFile.writeframes(b''.join(frames))
            waveFile.close()

            print("A Gravação terminou")

# inicializar flag de gravação e transmitir:
recording = False
stream = None
frames = None

# start keyboard event listener:
keyboard.on_press(on_press)

# mantenha o programa em execução até que o usuário pressione a tecla "q" para sair:
while True:
    if keyboard.is_pressed('q'):
        # Combinar todos os arquivos de áudio em um:
        print("Combining audio files...")
        with wave.open("output.wav", "wb") as outfile:
            for i in range(1, recording_counter):
                with wave.open(f"output_{i}.wav", "rb") as infile:
                    if i == 1:
                        outfile.setparams(infile.getparams())
                    outfile.writeframes(infile.readframes(infile.getnframes()))

        # Transcrever o áudio usando OpenAI API:
        audio_file= open("output.wav", "rb")
        transcript = openai.Audio.transcribe("whisper-1", audio_file, language="pt") 
        print(transcript["text"])

        break

# Lançar recursos PyAudio:
audio.terminate()

# Deletar arquivos de áudio individuais:
for i in range(1, recording_counter):
    os.remove(f"output_{i}.wav")