wujingjing
2025-04-09 678b137a19c2d096c82bef87962dd7df77f2855b
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
import { nextTick, onDeactivated, onMounted, ref } from 'vue';
import { SignJWT } from 'jose';
 
import './libs/duix.js';
import { questionStreamByPost } from '/@/api/ai/chat';
import { activeGroupType, activeRoomId } from '/@/stores/chatRoom';
import { markdownToTxt } from 'markdown-to-txt';
 
export type UseDigitalHumanProps = {
    container: string;
};
 
export const useDigitalHuman = (props: UseDigitalHumanProps) => {
    const { container } = props;
    const duixConfig = {
        appId: '1356792813207031808',
        appKey: '659b068e-900c-4fe5-bb96-3ca70fe0aae4',
        sign: '',
        conversationId: '1909088110274277378',
        /** @description 过期时间(小时) */
        expired: 12,
    };
 
    // 是否已接口相应
    const isReceiveRes = ref(false);
    const humanIsLoading = ref(true);
 
    const digitalHumanIsShow = ref(false);
    const closeDigitalHuman = () => {
        digitalHumanIsShow.value = false;
        resetDuixStatus();
    };
 
    const resetDuixStatus = () => {
        humanIsLoading.value = true;
        isReceiveRes.value = false;
        // isSpeaking.value = false;
        digitalHumanIsShow.value = false;
        duix?.stop();
    };
    const getPlainText = (item) => {
        let result = '';
        const knowledgeText = item.knowledge.reduce((acc, cur) => {
            const mdText = cur.answer;
            const linkText = cur.metadata?.Title;
            if (linkText) {
                return `${mdText}\n\n${linkText}`;
            }
            return acc + mdText;
        }, '');
        // const conclusionText =
        //     item.conclusion
        //         ?.filter((item) => !!item.report)
        //         .map((item) => item.report)
        //         .join('\n\n') ?? '';
        // result += knowledgeText + conclusionText;
        result = knowledgeText;
        return markdownToTxt(result);
    };
 
    let isWaitingSpeak = false;
 
    const speakContent = (content: string) => {
        // 打断之前的已收到xxx
        duix.break();
        isWaitingSpeak = false;
        duix.speak({
            content,
        });
    };
 
    const startDuix = () =>{
        const conversationId = duixConfig.conversationId; // duix平台会话id
 
        duix.start({ conversationId, openAsr: true,wipeGreen:true }).then((res) => {
            console.info('start', res);
        }).catch((err)=>{
            console.error('start error', err);
        });
    }
 
    const initDuix = () => {
        const sign = duixConfig.sign; // sign由服务端生成
        const conversationId = duixConfig.conversationId; // duix平台会话id
        if (!sign || !conversationId) {
            return alert('参数不能为空');
        }
        duix.on('error', (data) => {
            console.error(data);
        });
        duix.on('intialSucccess', () => {
            console.info('intialSucccess');
            // 此时初始化成功,可调用start
            startDuix();
        });
        duix.on('bye', (data) => {
            console.info('bye', data);
        });
        duix.on('progress', (progress) => {
            console.info('progress', progress);
        });
        duix.on('show', () => {
            console.info('show');
            humanIsLoading.value = false;
            // 此时可确认视频已
            // (document.querySelector('#modal') as HTMLElement).style.display = 'none';
        });
        duix.on('openAsrSuccess', () => {
            console.info('openAsrSuccess');
        });
        duix.on('asrClose', () => {
            console.info('asrClose');
        });
        duix.on('speakStart', (data) => {
            // isSpeaking.value = true;
            console.info('speakStart', data);
        });
        duix.on('speakEnd', (data) => {
            if (!isWaitingSpeak) {
                isReceiveRes.value = false;
                duix.openAsr().then((...a) => {
                });
            }
        });
        duix.on('speakSection', (data) => {
            console.info('speakSection', data);
        });
        duix.on('speakError', (data) => {
            console.info('speakError', data);
        });
        duix.on('asrResult', (data) => {
            console.info('asrResult', data);
            if (isReceiveRes.value) {
                return;
            }
            duix.closeAsr().then((...a) => {
            });
 
            let hasResult = false;
            isReceiveRes.value = true;
            try {
                isWaitingSpeak = true;
                duix.speak({
                    content: '已收到您的问题,正在思考中...请稍等',
                });
                questionStreamByPost(
                    {
                        question: data,
                        history_group_id: activeRoomId.value,
                        raw_mode: false,
                        group_type: activeGroupType.value,
                        is_digital_human: true,
                    },
                    (chunkRes) => {
                        if (chunkRes.mode === 'result' && chunkRes.value?.answer_type === 'knowledge') {
                            const plainText = getPlainText(chunkRes.value);
                            hasResult = true;
                            speakContent(plainText);
                        } else if (!chunkRes.value?.json_ok && chunkRes.value?.err_code === 'MESSAGE') {
                            if (hasResult) return;
                            hasResult = true;
                            speakContent(chunkRes.value.json_msg);
                        }
 
                        if (chunkRes.mode === 'finish') {
                            if (!hasResult) {
                                speakContent('暂时无法口头描述你所说的问题');
                            } else {
                                hasResult = false;
                            }
                            // isReceiveRes.value = false;
                        }
                    }
                );
            } catch (error) {
                console.error(error);
                isReceiveRes.value = false;
            }
        });
        duix.on('report', (data) => {
            // console.info('report', data)
        });
        duix
            .init({
                sign,
                containerLable: container,
            })
            .then((data) => {
                console.info('init', data);
            });
    };
 
    let hasInitDuix = false;
    let duix: any;
    const openDigitalHuman = () => {
        digitalHumanIsShow.value = true;
 
        nextTick(async () => {
            duixConfig.sign = await createSig(duixConfig.appId, duixConfig.appKey, 60 * 60 * duixConfig.expired);
            if (!hasInitDuix) {
                hasInitDuix = true;
 
                duix = new DUIX();
                initDuix();
            } else {
                startDuix();
            }
        });
    };
 
    function createSig(appId, appKey, sigExp) {
        const now = Math.floor(Date.now() / 1000);
        const expiresAt = now + sigExp;
 
        const sign = new SignJWT({ appId })
            .setProtectedHeader({ alg: 'HS256' })
            .setIssuedAt(now)
            .setExpirationTime(expiresAt)
            .sign(new TextEncoder().encode(appKey));
        return sign;
    }
 
    onMounted(() => {
        window.addEventListener('beforeunload', () => {
            closeDigitalHuman();
        });
    });
 
    onDeactivated(() => {
        closeDigitalHuman();
    });
 
    return {
        digitalHumanIsShow,
        openDigitalHuman,
        isHumanTalking: isReceiveRes,
        closeDigitalHuman,
        humanIsLoading,
    };
};