Spaces:
No application file
No application file
| """ | |
| 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") | |