Skip to content

Commit

Permalink
feat: openai tts
Browse files Browse the repository at this point in the history
  • Loading branch information
dragon-fish committed Nov 10, 2023
1 parent 781106d commit 1cadee8
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
"koishi-plugin-schedule": "^5.0.0",
"koishi-plugin-switch": "^1.2.0",
"mint-filter": "^4.0.3",
"openai": "^4.14.0",
"openai": "^4.17.2",
"wiki-saikou": "^3.2.1"
}
}
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 38 additions & 1 deletion src/plugins/openai/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @license MIT
*/

import { Context, Session, Time } from 'koishi'
import { Context, Session, Time, arrayBufferToBase64 } from 'koishi'
import { OpenAI, ClientOptions } from 'openai'
import BasePlugin from '../_boilerplate'
import { readFileSync, writeFileSync } from 'fs'
Expand Down Expand Up @@ -286,6 +286,7 @@ export default class PluginOpenAi extends BasePlugin {
)
})
})

this.ctx
.command('openai/chat.reset', '开始新的对话')
.userFields(['openai_last_conversation_id'])
Expand All @@ -311,6 +312,27 @@ export default class PluginOpenAi extends BasePlugin {
)
}
})

this.ctx
.command('openai.tts <input:text>', '说话', {
maxUsage: 3,
bypassAuthority: 3,
})
.option('voice', '-v <voice:string>')
.option('speed', '-s <speed:number>')
.action(async ({ options }, input) => {
if (!input) {
return 'SILI不知道你想说什么呢。'
}

options = Object.fromEntries(
Object.entries(options).filter(([, val]) => !!val)
)

const buffer = await this.createTTS(input, options as any)
const base64 = arrayBufferToBase64(buffer)
return <audio url={`data:audio/mp3;base64,${base64}`}></audio>
})
}

async reviewConversation(
Expand Down Expand Up @@ -348,6 +370,21 @@ export default class PluginOpenAi extends BasePlugin {
})
}

async createTTS(
input: string,
options?: Partial<OpenAI.Audio.Speech.SpeechCreateParams>
) {
const data = await this.openai.audio.speech.create({
model: 'tts-1',
voice: 'alloy',
input,
response_format: 'mp3',
speed: 1,
...options,
})
return data.arrayBuffer()
}

static readPromptFile(file: string) {
try {
return readFileSync(resolve(__dirname, `./prompts/${file}`), {
Expand Down

0 comments on commit 1cadee8

Please sign in to comment.