-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathChatOperationButton.vue
More file actions
551 lines (531 loc) · 15.7 KB
/
ChatOperationButton.vue
File metadata and controls
551 lines (531 loc) · 15.7 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
<template>
<div class="chat-operation-button flex-between">
<el-text type="info">
<span class="ml-4">{{ datetimeFormat(data.create_time) }}</span>
</el-text>
<div>
<!-- 语音播放 -->
<span v-if="tts">
<el-tooltip
v-if="audioManage?.isPlaying()"
effect="dark"
:content="$t('chat.operation.pause')"
placement="top"
>
<el-button
type="primary"
text
:disabled="!data?.write_ed"
@click="audioManage?.pause(true)"
>
<AppIcon iconName="app-video-pause"></AppIcon>
</el-button>
</el-tooltip>
<el-tooltip effect="dark" :content="$t('chat.operation.play')" placement="top" v-else>
<el-button
text
:disabled="!data?.write_ed"
@click="
() => {
bus.emit('play:pause', props.data.record_id)
audioManage?.play(props.data.answer_text, true, true)
}
"
>
<AppIcon iconName="app-video-play"></AppIcon>
</el-button>
</el-tooltip>
<el-divider direction="vertical" />
</span>
<span v-if="type == 'ai-chat' || type == 'log'">
<el-tooltip effect="dark" :content="$t('common.copy')" placement="top">
<el-button text @click="copy(data)">
<AppIcon iconName="app-copy"></AppIcon>
</el-button>
</el-tooltip>
<el-divider direction="vertical" />
<el-tooltip effect="dark" :content="$t('chat.operation.regeneration')" placement="top">
<el-button :disabled="chat_loading" text @click="regeneration">
<el-icon><RefreshRight /></el-icon>
</el-button>
</el-tooltip>
<el-divider direction="vertical" />
<el-tooltip
effect="dark"
:content="$t('chat.operation.like')"
placement="top"
v-if="buttonData?.vote_status === '-1'"
>
<el-button text @click="voteHandle('0')" :disabled="loading">
<AppIcon iconName="app-like"></AppIcon>
</el-button>
</el-tooltip>
<el-tooltip
effect="dark"
:content="$t('chat.operation.cancelLike')"
placement="top"
v-if="buttonData?.vote_status === '0'"
>
<el-button text @click="voteHandle('-1')" :disabled="loading">
<AppIcon iconName="app-like-color"></AppIcon>
</el-button>
</el-tooltip>
<el-divider direction="vertical" v-if="buttonData?.vote_status === '-1'" />
<el-tooltip
effect="dark"
:content="$t('chat.operation.oppose')"
placement="top"
v-if="buttonData?.vote_status === '-1'"
>
<el-button text @click="voteHandle('1')" :disabled="loading">
<AppIcon iconName="app-oppose"></AppIcon>
</el-button>
</el-tooltip>
<el-tooltip
effect="dark"
:content="$t('chat.operation.cancelOppose')"
placement="top"
v-if="buttonData?.vote_status === '1'"
>
<el-button text @click="voteHandle('-1')" :disabled="loading">
<AppIcon iconName="app-oppose-color"></AppIcon>
</el-button>
</el-tooltip>
</span>
<div ref="audioCiontainer"></div>
</div>
</div>
</template>
<script setup lang="ts">
import { nextTick, onMounted, ref, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import { copyClick } from '@/utils/clipboard'
import applicationApi from '@/api/application'
import { datetimeFormat } from '@/utils/time'
import { MsgError } from '@/utils/message'
import bus from '@/bus'
const copy = (data: any) => {
try {
const text = data.answer_text_list
.map((item: Array<any>) => item.map((i) => i.content).join('\n'))
.join('\n\n')
copyClick(removeFormRander(text))
} catch (e: any) {
copyClick(removeFormRander(data?.answer_text.trim()))
}
}
const route = useRoute()
const {
params: { id }
} = route as any
const props = withDefaults(
defineProps<{
data: any
type: 'log' | 'ai-chat' | 'debug-ai-chat'
chatId: string
chat_loading: boolean
applicationId: string
tts: boolean
tts_type: string
tts_autoplay: boolean
}>(),
{
data: () => ({}),
type: 'ai-chat'
}
)
const emit = defineEmits(['update:data', 'regeneration'])
const audioPlayer = ref<HTMLAudioElement[] | null>([])
const audioCiontainer = ref<HTMLDivElement>()
const buttonData = ref(props.data)
const loading = ref(false)
const audioList = ref<string[]>([])
function regeneration() {
emit('regeneration')
}
function voteHandle(val: string) {
applicationApi
.putChatVote(props.applicationId, props.chatId, props.data.record_id, val, loading)
.then(() => {
buttonData.value['vote_status'] = val
emit('update:data', buttonData.value)
})
}
function markdownToPlainText(md: string) {
return (
md
// 移除图片 
.replace(/!\[.*?\]\(.*?\)/g, '')
// 移除链接 [text](url)
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
// 移除 Markdown 标题符号 (#, ##, ###)
.replace(/^#{1,6}\s+/gm, '')
// 移除加粗 **text** 或 __text__
.replace(/\*\*(.*?)\*\*/g, '$1')
.replace(/__(.*?)__/g, '$1')
// 移除斜体 *text* 或 _text_
.replace(/\*(.*?)\*/g, '$1')
.replace(/_(.*?)_/g, '$1')
// 移除行内代码 `code`
.replace(/`(.*?)`/g, '$1')
// 移除代码块 ```code```
.replace(/```[\s\S]*?```/g, '')
// 移除多余的换行符
.replace(/\n{2,}/g, '\n')
.trim()
)
}
function removeFormRander(text: string) {
return text.replace(/<form_rander>[\s\S]*?<\/form_rander>/g, '').trim()
}
function getKey(keys: Array<number>, index: number) {
// 从后往前查找第一个小于等于index的键
for (let i = keys.length - 1; i >= 0; i--) {
if (keys[i] <= index) {
return keys[i]
}
}
return 0
}
function smartSplit(
str: string,
minLengthConfig: any = {
0: 10,
1: 25,
3: 50,
5: 100
},
is_end = false
) {
// 匹配中文逗号/句号,且后面至少还有20个字符(含任何字符,包括换行)
const regex = /([。?\n])|(<audio[^>]*><\/audio>)/g
// 拆分并保留分隔符
const parts = str.split(regex)
const result = []
const keys = Object.keys(minLengthConfig).map(Number)
let minLength = minLengthConfig[0]
let temp_str = ''
for (let i = 0; i < parts.length; i++) {
const content = parts[i]
if (content == undefined) {
continue
}
if (/^<audio[^>]*><\/audio>$/.test(content)) {
if (temp_str.length > 0) {
result.push(temp_str)
temp_str = ''
}
result.push(content)
continue
}
temp_str += parts[i]
if (temp_str.length > minLength && /[。?\n]$/.test(temp_str)) {
minLength = minLengthConfig[getKey(keys, i)]
result.push(temp_str)
temp_str = ''
}
}
if (temp_str.length > 0 && is_end) {
result.push(temp_str)
}
return result
}
enum AudioStatus {
/**
* 结束
*/
END = 'END',
/**
* 播放中
*/
PLAY_INT = 'PLAY_INT',
/**
* 刚挂载
*/
MOUNTED = 'MOUNTED',
/**
* 就绪
*/
READY = 'READY',
/**
* 错误
*/
ERROR = 'ERROR'
}
class AudioManage {
textList: Array<string>
statusList: Array<AudioStatus>
audioList: Array<HTMLAudioElement | SpeechSynthesisUtterance>
tryList: Array<number>
ttsType: string
root: Element
is_end: boolean
constructor(ttsType: string, root: HTMLDivElement) {
this.textList = []
this.audioList = []
this.statusList = []
this.tryList = []
this.ttsType = ttsType
this.root = root
this.is_end = false
}
appendTextList(textList: Array<string>) {
const newTextList = textList.slice(this.textList.length)
// 没有新增段落
if (newTextList.length <= 0) {
return
}
newTextList.forEach((text, index) => {
this.textList.push(text)
this.statusList.push(AudioStatus.MOUNTED)
this.tryList.push(1)
index = this.textList.length - 1
if (this.ttsType === 'TTS') {
const audioElement: HTMLAudioElement = document.createElement('audio')
audioElement.controls = false
audioElement.hidden = true
/**
* 播放结束事件
*/
audioElement.onended = () => {
this.statusList[index] = AudioStatus.END
// 如果所有的节点都播放结束
if (this.statusList.every((item) => item === AudioStatus.END) && this.is_end) {
this.statusList = this.statusList.map((item) => AudioStatus.READY)
this.is_end = false
} else {
// next
this.play()
}
}
this.root.appendChild(audioElement)
if (/^<audio[^>]*><\/audio>$/.test(text)) {
audioElement.src = text.match(/src="([^"]*)"/)?.[1] || ''
this.statusList[index] = AudioStatus.READY
} else {
applicationApi
.postTextToSpeech(
(props.applicationId as string) || (id as string),
{ text: text },
loading
)
.then(async (res: any) => {
if (res.type === 'application/json') {
const text = await res.text()
if (this.tryList[index] >= 3) {
MsgError(text)
}
this.statusList[index] = AudioStatus.ERROR
throw ''
}
// 假设我们有一个 MP3 文件的字节数组
// 创建 Blob 对象
const blob = new Blob([res], { type: 'audio/mp3' })
// 创建对象 URL
const url = URL.createObjectURL(blob)
audioElement.src = url
this.statusList[index] = AudioStatus.READY
this.play()
})
.catch((err) => {
this.statusList[index] = AudioStatus.ERROR
this.play()
})
}
this.audioList.push(audioElement)
} else {
const speechSynthesisUtterance: SpeechSynthesisUtterance = new SpeechSynthesisUtterance(
text
)
speechSynthesisUtterance.onend = () => {
this.statusList[index] = AudioStatus.END
// 如果所有的节点都播放结束
if (this.statusList.every((item) => item === AudioStatus.END)) {
this.statusList = this.statusList.map((item) => AudioStatus.READY)
} else {
// next
this.play()
}
}
speechSynthesisUtterance.onerror = (e) => {
this.statusList[index] = AudioStatus.READY
}
this.statusList[index] = AudioStatus.READY
this.audioList.push(speechSynthesisUtterance)
this.play()
}
})
}
reTryError() {
this.statusList.forEach((status, index) => {
if (status === AudioStatus.ERROR && this.tryList[index] <= 3) {
this.tryList[index]++
const audioElement = this.audioList[index]
if (audioElement instanceof HTMLAudioElement) {
const text = this.textList[index]
this.statusList[index] = AudioStatus.MOUNTED
applicationApi
.postTextToSpeech(
(props.applicationId as string) || (id as string),
{ text: text },
loading
)
.then(async (res: any) => {
if (res.type === 'application/json') {
const text = await res.text()
if (this.tryList[index] >= 3) {
MsgError(text)
}
throw ''
}
// 假设我们有一个 MP3 文件的字节数组
// 创建 Blob 对象
const blob = new Blob([res], { type: 'audio/mp3' })
// 创建对象 URL
const url = URL.createObjectURL(blob)
audioElement.src = url
this.statusList[index] = AudioStatus.READY
this.play()
})
.catch((err) => {
console.log('err: ', err)
this.statusList[index] = AudioStatus.ERROR
this.play()
})
}
}
})
}
isPlaying() {
return this.statusList.some((item) => [AudioStatus.PLAY_INT].includes(item))
}
play(text?: string, is_end?: boolean, self?: boolean) {
if (is_end) {
this.is_end = true
}
if (self) {
this.tryList = this.tryList.map((item) => 0)
}
if (text) {
const textList = this.getTextList(text, is_end ? true : false)
this.appendTextList(textList)
}
// 如果存在在阅读的元素则直接返回
if (this.statusList.some((item) => [AudioStatus.PLAY_INT].includes(item))) {
return
}
this.reTryError()
// 需要播放的内容
const index = this.statusList.findIndex((status) =>
[AudioStatus.MOUNTED, AudioStatus.READY].includes(status)
)
if (index < 0 || this.statusList[index] === AudioStatus.MOUNTED) {
return
}
const audioElement = this.audioList[index]
if (audioElement instanceof HTMLAudioElement) {
// 标签朗读
try {
this.statusList[index] = AudioStatus.PLAY_INT
const play = audioElement.play()
if (play instanceof Promise) {
play.catch((e) => {
this.statusList[index] = AudioStatus.READY
})
}
} catch (e: any) {
this.statusList[index] = AudioStatus.ERROR
}
} else {
if (window.speechSynthesis.paused) {
window.speechSynthesis.resume()
} else {
if (window.speechSynthesis.pending) {
window.speechSynthesis.cancel()
}
speechSynthesis.speak(audioElement)
this.statusList[index] = AudioStatus.PLAY_INT
}
}
}
pause(self?: boolean) {
const index = this.statusList.findIndex((status) => status === AudioStatus.PLAY_INT)
if (index < 0) {
return
}
const audioElement = this.audioList[index]
if (audioElement instanceof HTMLAudioElement) {
if (this.statusList[index] === AudioStatus.PLAY_INT) {
// 标签朗读
this.statusList[index] = AudioStatus.READY
audioElement.pause()
}
} else {
this.statusList[index] = AudioStatus.READY
if (self) {
window.speechSynthesis.pause()
nextTick(() => {
if (!window.speechSynthesis.paused) {
window.speechSynthesis.cancel()
}
})
} else {
window.speechSynthesis.cancel()
}
}
}
getTextList(text: string, is_end: boolean) {
// 移除表单渲染器
text = removeFormRander(text)
// text 处理成纯文本
text = markdownToPlainText(text)
const split = smartSplit(
text,
{
0: 20,
1: 50,
5: 100
},
is_end
)
return split
}
}
const audioManage = ref<AudioManage>()
onMounted(() => {
if (audioCiontainer.value) {
audioManage.value = new AudioManage(props.tts_type, audioCiontainer.value)
}
bus.on('play:pause', (record_id: string) => {
if (record_id !== props.data.record_id) {
if (audioManage.value) {
audioManage.value?.pause()
}
}
})
bus.on('change:answer', (data: any) => {
const record_id = data.record_id
bus.emit('play:pause', record_id)
if (props.data.record_id == record_id) {
if (props.tts && props.tts_autoplay) {
if (audioManage.value) {
audioManage.value.play(props.data.answer_text, data.is_end)
}
}
}
})
})
onBeforeUnmount(() => {
if (audioManage.value) {
audioManage.value.pause()
}
})
</script>
<style lang="scss" scoped>
@media only screen and (max-width: 430px) {
.chat-operation-button {
display: block;
text-align: right;
}
}
</style>