このチャプターの目次
音声認識は Whisper を使用します。
Whisper とは
Whisper は、OpenAI が開発した音声認識モデルです。
最新のディープラーニング技術を使用して、高精度な音声認識を実現しています。
大量の音声データを学習し、音声の特徴を自動的に抽出することで、より正確な音声認識を行います。
Whisper は、オンラインでの会話や音声通話、音声コマンドの認識など、さまざまな用途に使用されます。
音声から文字起こしと翻訳処理をすることができます。
Whisper API
api フォルダにwhisper.ts
ファイルを作成します。
pages/api/whisper.ts
import { Configuration, OpenAIApi } from 'openai'
import type { NextApiRequest, NextApiResponse } from 'next'
import formidable, { File } from 'formidable'
import fs from 'fs'
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
})
const openai = new OpenAIApi(configuration)
const form = formidable({ multiples: true, keepExtensions: true })
const isFile = (file: File | File[]): file is File => {
return !Array.isArray(file) && file?.filepath !== undefined
}
export const config = {
api: {
bodyParser: false,
},
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const fileContent: any = await new Promise((resolve, reject) => {
form.parse(req, (err, _fields, files) => {
if (isFile(files.file)) {
resolve(fs.createReadStream(files.file.filepath))
}
return reject('file is not found')
})
})
// Whisper
const response = await openai.createTranscription(fileContent, 'whisper-1')
const transcript = response.data.text
res.status(200).json({ transcript })
} catch (error) {
console.error(error)
res.status(500).send('Something went wrong')
}
}
createTranscription
音声認識は、openai.createTranscription
を使用します。
第 1 引数に File を設定します。
fileContent には、ファイルが読み込まれていることを確認し、読み込まれていた場合は、fs.createReadStream
を使用してストリームとして返しています。
bodyParser オプションを false に設定する必要があります。
第 2 引数にモデルwhisper-1
を指定します。
他にも引数があるので、公式ドキュメントで確認してみてください。