
如何在 Apifox 中發布多語言的 API 文檔?
麥克風權限
在我們開始錄制音頻之前,請確保獲得訪問麥克風的必要權限。
對于 Windows
對于 MacOS
設置
我們需要幾個庫來錄制和處理音頻。
要安裝先決條件,只需運行以下代碼片段。
# Prerequisites for the Python Modules
!brew install ffmpeg
!brew install portaudio
# Audio Processing
%pip install -q simpleaudio
%pip install -q pyaudio
%pip install -q wave
# Clipboard Management
%pip install -q pyperclip
# Speech Transcriber
%pip install -q openai
%pip install -q openai --upgrade # fix for Cannot import name 'OpenAI' from 'openai'
# Securing API keys
%pip install -q python-dotenv
我們將創建一個處理錄音的函數。此功能將支持手動和定時錄音:
temp_file = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
temp_file_name = temp_file.name
2. 回調函數。 此函數在錄音時將音頻數據寫入臨時文件。
def callback(data_input, frame_count, time_info, status):
wav_file.writeframes(data_input)
return None, pyaudio.paContinue
3. 錄制音頻。 我們設置麥克風來捕捉音頻并將其保存到臨時文件中。
打開 .wav 文件進行寫入。設置音頻格式:1 通道、16 位樣本和 16000 Hz 采樣率。
這些值是語音識別任務的標準:
初始化 PyAudio 并開始錄音。
import pyaudio
import wave
import tempfile
import time
def record_audio(timed_recording=False, record_seconds=5):
temp_file = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
temp_file_name = temp_file.name
def callback(data_input, frame_count, time_info, status):
wav_file.writeframes(data_input)
return None, pyaudio.paContinue
with wave.open(temp_file_name, "wb") as wav_file:
wav_file.setnchannels(1) # Mono channel
wav_file.setsampwidth(2) # 16-bit samples
wav_file.setframerate(16000) # 16kHz sample rate
audio = pyaudio.PyAudio()
stream = audio.open(
format=pyaudio.paInt16,
channels=1,
rate=16000,
input=True,
frames_per_buffer=1024,
stream_callback=callback,
)
if timed_recording:
print(f"Recording for {record_seconds} seconds...")
time.sleep(record_seconds)
else:
input("Press Enter to stop recording...")
stream.stop_stream()
stream.close()
audio.terminate()
return temp_file_name
此函數允許我們記錄特定持續時間(timed_recording=True)或直到用戶按下 Enter(timed_recording=False)。
現在,讓我們創建一個函數來處理轉錄(用于英語)和翻譯(用于非英語音頻):
1.導入 OpenAI 庫
我們使用 OpenAI 庫來訪問 Audio Whisper API。要使用 OpenAI API,您需要設置 API 密鑰。您可以從 OpenAI 網站獲取 API 密鑰。
出于安全考慮,請在項目目錄中創建一個 .env 文件并將 OpenAI API 密鑰存儲在那里。這樣,您就避免直接在代碼中硬編碼敏感信息。
1. 在與筆記本相同的目錄中創建一個.env 文件。
2. 將您的 OpenAI API 密鑰添加到 .env 文件中,格式如下:
OPEN_AI_API_KEY=your_actual_api_key_here
3. 使用 dotenv 庫在筆記本中加載環境變量。
獲得密鑰后,您可以按如下方式在代碼中進行設置:
from openai import OpenAI
from dotenv import load_dotenv
import os
# Load the OpenAI API key from the .env file
load_dotenv()
openai_api_key = os.getenv("OPEN_AI_API_KEY")
# Set up your OpenAI API client
client = OpenAI(api_key=openai_api_key)
2. 轉錄音頻
打開錄制的音頻文件并將其發送到 OpenAI Audio Whisper API 進行轉錄。API 返回文本。
def process_audio(file_name, is_english=True, prompt=""):
with open(file_name, "rb") as audio_file:
if is_english:
response = client.audio.transcriptions.create(
model="whisper-1", file=audio_file, prompt=prompt
)
else:
response = client.audio.translations.create(
model="whisper-1", file=audio_file
)
return response.text.strip()
注意: 您可以使用提示來指導您錄制時的轉錄。這有多種用途,例如拼寫糾正、語言規范、首字母縮略詞識別、填充詞刪除或添加、標點符號等等。
請查看 Audio Whisper API 的參考資料以了解更多信息。或者,您也可以查看 prestontuggle 的 AI Cookbook Recipe 。
1.導入 pyperclip
這個庫有助于將文本復制到剪貼板。
import pyperclip
2. 復制轉錄
將轉錄的文本復制到剪貼板并打印確認信息。
def copy_to_clipboard(text):
pyperclip.copy(text)
print("Result copied to clipboard!")
這是錄制音頻、轉錄并將結果文本復制到剪貼板的完整功能。
import simpleaudio as sa
import os
def transcribe_audio(
debug: bool = False,
prompt: str = "",
timed_recording: bool = False,
record_seconds: int = 5,
is_english: bool = True,
) -> str:
"""
Records audio from the microphone and transcribes or translates it using OpenAI's API.
Args:
debug (bool): If True, plays back the recorded audio for verification.
prompt (str): A prompt to guide the transcription (only used for English).
timed_recording (bool): If True, records for a set duration. If False, records until user input.
record_seconds (int): The number of seconds to record if timed_recording is True.
is_english (bool): If True, uses transcription. If False, uses translation to English.
Returns:
str: The transcription or translation of the recorded audio.
"""
# Record audio
temp_file_name = record_audio(timed_recording, record_seconds)
# Debug playback
if debug:
print("Playing back recorded audio...")
playback = sa.WaveObject.from_wave_file(temp_file_name)
play_obj = playback.play()
play_obj.wait_done()
# Process audio (transcribe or translate)
result = process_audio(temp_file_name, is_english, prompt)
# Clean up temporary file
os.remove(temp_file_name)
# Copy result to clipboard
copy_to_clipboard(result)
return result
演示
# Demo: Transcribe 5 seconds of spoken English with proper grammar and punctuation
result = transcribe_audio(
debug=True,
prompt="English spoken. Proper grammar and punctuation. Skip fillers.",
timed_recording=True,
record_seconds=5,
is_english=True,
)
print("\nTranscription/Translation:", result)
如果遇到問題,請確保:
? 您的麥克風已正確設置并已授予權限。
? OpenAI API 密鑰有效且在您的 .env 文件中正確設置。
? 您正在使用正確版本的庫。
1. 我可以錄制超過 5 分鐘嗎?
是的,將 record_seconds 參數調整為更長的持續時間。
2. Whisper 支持哪些音頻格式?
Whisper 支持多種音頻格式;但為了獲得最佳性能,建議使用 .wav。
3. 有沒有辦法轉錄英語以外的其他語言?
是的,只需將 is_english 參數設置為 False 即可使用 Whisper 的翻譯功能。
使用這些代碼片段,您可以輕松地從設備麥克風錄制音頻,使用 OpenAI 的 Whisper API 轉錄或翻譯音頻,并將結果復制到剪貼板。您可以擴展或修改這些函數以獲得其他功能,例如用戶界面或與其他應用程序集成。
文章轉載自:Using Whisper API to transcribe text using your Device Microphone