-
Notifications
You must be signed in to change notification settings - Fork 31
/
live2d_llm_edge_tts.html
685 lines (447 loc) · 15.1 KB
/
live2d_llm_edge_tts.html
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
<html>
<head>
<script src="./js/live2dcubismcore.min.js"></script>
<script src="./js/live2d.min.js"></script>
<script src="./js/pixi.min.js"></script>
<!-- if only Cubism 4 support-->
<script src="./js/cubism4.min.js"></script>
<script src="./js/jquery-3.1.1.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<canvas id=canvas></canvas>
<div id="control">
<button id="play">测试音频</button> <button onclick="JavaScript:window.location.href='/'">返回菜单</button>
<br />
<label>数字人模型</label>
<select id="model_list"></select> <button id="update_model">更新模型</button>
<br />
<label>眼神跟随鼠标</label>
<input type="radio" name="eyes" value="true" checked >
<label>跟随鼠标</label><input type="radio" id="option2" name="eyes" value="false" ><label >前方直视</label>
<br />
<label>背景控制</label>
<input type="radio" id="option1" name="options" value="bg_color" checked >
<label for="option1">背景颜色</label><input id="bg_color" type="text" style="width:100px;" ><br /><input type="radio" id="option2" name="options" value="bg_img" ><label for="option2">背景图片</label> <input type="file" id="imgupload" style="display:none"/>
<button id="openImgUpload">上传图片</button> <button id="update_bg">更新背景</button>
<br />
<label>角色</label>
<select id="speaker">
<option value="zh-CN-XiaoxiaoNeural" selected>晓晓</option>
<option value="zh-CN-XiaoyiNeural" >晓依</option>
<option value="zh-CN-liaoning-XiaobeiNeural" >晓北(东北)</option>
<option value="zh-TW-HsiaoChenNeural" >晓晨(台湾)</option>
<option value="zh-TW-HsiaoYuNeural" >晓雨(台湾)</option>
</select>
<br />
<label>ollama接口地址</label>
<input type="search" id="llmurl" style="width:300px;" value="http://localhost:11434/api/chat" >
<label>模型名称</label>
<input id="model_name" value="nsfw" >
<br />
<label>引导词(以AI的视角)</label>
<input id="role_card" style="width:300px;" value="亲爱的,我是你的性感女友,我会为了你做任何事情。">
<br />
<label>对话长度</label><input id="tokens" value="50"> <label>temperature温度</label><input id="temperature" value="0.7">
<br />
<label>聊天文本</label>
<input id="text" style="width:300px;" value=""> <button id="start_talk">发送消息</button>
<br /><br />
<textarea id="text_talk" style="width:400px;height:200px;font-size:15px;"></textarea>
<button id="start">合成语音</button>
</div>
<script type="text/javascript">
// $("#start_stream").hide()
$('#text').keypress(function(e) {
if (e.which == 13) { // 检查是否按下了回车键
$('#start_talk').click(); // 触发按钮点击事件
return false; // 阻止默认行为
}
});
$('input[name="eyes"]').click(function(){
var radioValue = $("input[name='eyes']:checked").val();
setCookie("eyes", radioValue, 1024);
location.reload();
});
$('#openImgUpload').click(function(){
$('#imgupload').trigger('click');
});
$('#imgupload').on('change', function(){
var formData = new FormData();
formData.append('image', $(this)[0].files[0]);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('上传成功: ');
console.log(data.filename);
setCookie("bg_img", data.filename, 1024);
var radioValue = $("input[name='options']:checked").val();
setCookie("bg_con", radioValue, 1024);
location.reload();
}
});
});
// 从 cookie 中获取保存的值
function getCookie(name) {
const value = "; " + document.cookie;
const parts = value.split("; " + name + "=");
if (parts.length === 2) return parts.pop().split(";").shift();
}
// 将选中的值写入 cookie
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
// 控制背景色
// 读取 cookie 中的值并设置单选按钮的选中状态
const selectedValue = getCookie("bg_con");
if (selectedValue) {
const radioButtons = document.getElementsByName("options");
radioButtons.forEach(radio => {
radio.checked = false;
if (radio.value === selectedValue) {
radio.checked = true;
}
});
}
// 读取 cookie 中的值并设置单选按钮的选中状态
const eyesValue = getCookie("eyes");
if (eyesValue) {
const radioButtons = document.getElementsByName("eyes");
radioButtons.forEach(radio => {
radio.checked = false;
if (radio.value == eyesValue) {
radio.checked = true;
}
});
}
// 设置背景色
let radioValue = $("input[name='options']:checked").val();
if (getCookie("bg_color") === undefined) {$("#bg_color").val("gray");}else{$("#bg_color").val(getCookie("bg_color"));}
if(radioValue == "bg_color"){
$("#canvas").css("background-color",$("#bg_color").val());
}else{
if (getCookie("bg_img") === undefined) {
}else{
let imageUrl = "./uploads/"+getCookie("bg_img");
$("#canvas").css("background-image", "url(" + imageUrl + ")");
// $("#canvas").css("background-repeat","space");
}
}
let eye_bool = true;
if (getCookie("eyes") === undefined) {}else{
if (getCookie("eyes")=="false"){
eye_bool = false;
}
}
// 数字人模型
var cubism4Model = './models/<%=model_path%>/<%=model_path%>.model3.json';
var selected_model = '<%-model_path%>';
var model_list = '<%-model_list%>';
model_list = JSON.parse(model_list);
var $select = $("#model_list");
$select.empty(); // 清空旧选项
// 遍历新选项列表并添加到select元素中
$.each(model_list, function(index, value) {
if (value==selected_model){
$select.append($("<option selected></option>").attr("value", value).text(value));
}else{
$select.append($("<option></option>").attr("value", value).text(value));
}
});
// const cubism4Model = "./Hiyori/Hiyori.model3.json";
// const cubism4Model = "./March 7th/March 7th.model3.json";
const live2d = PIXI.live2d;
(async function main() {
const app = new PIXI.Application({
view: document.getElementById("canvas"),
autoStart: true,
resizeTo: window,
transparent: true,
backgroundAlpha: 0,
});
var models = await Promise.all([
live2d.Live2DModel.from(cubism4Model,{ autoInteract: eye_bool })
]);
models.forEach((model) => {
app.stage.addChild(model);
const scaleX = (innerWidth ) / model.width;
const scaleY = (innerHeight ) / model.height;
// fit the window
model.scale.set(Math.min(scaleX, scaleY));
model.y = innerHeight * 0.1;
draggable(model);
// addFrame(model);
// addHitAreaFrames(model);
// talk(model)
});
const model4 = models[0];
model4.x = innerWidth / 2;
model4.on("hit", (hitAreas) => {
if (hitAreas.includes("Body")) {
model4.motion("Tap");
}
if (hitAreas.includes("Head")) {
model4.expression();
}
});
// 更新背景
$("#update_bg").click(function() {
var radioValue = $("input[name='options']:checked").val();
setCookie("bg_con", radioValue, 1024);
setCookie("bg_color", $("#bg_color").val(), 1024);
location.reload();
});
// 更新模型
$("#update_model").click(function() {
axios.get('/edit_config',{
params: {"model_path":$("#model_list").val()}
})
.then(response => {
// 处理成功响应
console.log(response.data);
location.reload();
})
.catch(error => {
// 处理错误
console.error(error);
alert(error);
});
});
$("#play").click(function() {
talk(model4,"./Keira.wav");
});
$("#stop").click(function() {
model4.stopSpeaking();
});
$("#start").click(function() {
console.log($("#text_talk").val());
let text = $("#text_talk").val().trim();
$("#start").prop("disabled", true);
axios.defaults.timeout = 300000;
axios.get("http://localhost:3000/edge_tts", {
params: {
text: text,
speaker:$("#speaker").val()
}
}, {
responseType: 'arraybuffer'
})
.then(response => {
console.log(response.data.audio);
const base64Audio = response.data.audio;
// 将 Base64 数据解码为 ArrayBuffer
const audioData = Uint8Array.from(atob(base64Audio), c => c.charCodeAt(0)).buffer;
// 创建 Blob 对象
const audioBlob = new Blob([audioData], { type: 'audio/wav' });
// 创建 URL 对象
const audioUrl = URL.createObjectURL(audioBlob);
// 创建一个新的Audio对象并播放音频
// const audio = new Audio(audioUrl);
// audio.play();
talk(model4,audioUrl);
$("#start").prop("disabled",false);
})
.catch(error => {
console.error('请求接口失败:', error);
$("#start").prop("disabled",false);
});
});
$("#start_talk").click(async function() {
console.log($("#text").val());
let text = $("#text").val().trim();
if(text == ""){
alert("请输入聊天内容");
return false;
}
$("#start_talk").prop("disabled", true);
const data = {
"model":$("#model_name").val(),"stream":true,
"messages": [
{
"role": "assistant",
"content": $("#role_card").val()
},
{
"role": "user",
"content": $("#text").val()
}
],
"options": {
"num_keep": 5,
"num_predict": 100,
"top_k": 40,
"top_p": 0.95,
//"tfs_z": 0.5,
//"typical_p": 0.7,
//"repeat_last_n": 33,
"temperature": parseFloat($("#temperature").val()),
"repeat_penalty": 1,
// "presence_penalty": 1.5,
// "frequency_penalty": 1.0,
// "mirostat": 1,
// "mirostat_tau": 0.7,
// "mirostat_eta": 0.6,
"penalize_newline": true,
"numa": false,
"num_predict": parseInt($("#tokens").val()),
"num_thread": 8
}
}
$("#text_talk").val(""); // 清空旧选项
const response = await fetch($("#llmurl").val(), {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
},
});
const reader = response.body?.pipeThrough(new TextDecoderStream()).getReader();
while (true) {
let { done, value } = await reader.read();
if (done) {
console.log("***********************done");
$("#start_talk").prop("disabled",false);
$("#start").click();
break;
}
console.log("--------------------value");
try {
value = JSON.parse(value);
//console.log(value);
// 在这里可以使用parsedValue变量
const text = value.message.content;
$('#text_talk').val($('#text_talk').val() + text);
} catch (error) {
console.error("JSON 解析出错: " + error);
}
}
});
$("#start_stream").click(async function() {
console.log($("#text_talk").val());
let text = $("#text").val().trim();
$("#start_stream").prop("disabled", true);
data = {text_lang: $("#text_lang").val(),
ref_audio_path: $("#ref_audio_path").val(),
prompt_lang: $("#prompt_lang").val(),
prompt_text: $("#prompt_text").val(),
text_split_method: $("#text_split_method").val(),
batch_size: 1,
media_type: 'ogg',
speed_factor: $("#speed_factor").val(),
text: $("#text_talk").val(),
streaming_mode:"true"}
const response = await fetch($("#apiurl").val(), {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
},
});
const reader = response.body.getReader();
const context = new (window.AudioContext || window.webkitAudioContext)();
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) {
console.log("***********************done");
$("#start_stream").prop("disabled", false);
break;
}
console.log("--------------------value");
console.log(value);
// 将返回的音频数据转换为Blob对象
const audioBlob = new Blob([value.buffer], { type: 'audio/ogg' });
// 创建一个URL对象用于播放音频
const audioUrl = URL.createObjectURL(audioBlob);
talk(model4,audioUrl);
// 将读取到的值添加到数组中
//chunks.push(value);
}
// // 合并所有读取到的二进制数据
// const audioBuffer = new Uint8Array(chunks.reduce((acc, val) => acc.concat(Array.from(val)), []));
// // 解码音频数据并播放
// context.decodeAudioData(audioBuffer.buffer).then(decodedData => {
// const source = context.createBufferSource();
// source.buffer = decodedData;
// source.connect(context.destination);
// source.start(0);
// }).catch(error => {
// console.error("Error decoding audio data:", error);
// });
});
})();
function talk(model,audio){
var audio_link = audio; //[Optional arg, can be null or empty] [relative or full url path] [mp3 or wav file] "./Keira.wav"
var volume = 1; // [Optional arg, can be null or empty] [0.0 - 1.0]
var expression = 8; // [Optional arg, can be null or empty] [index|name of expression]
var resetExpression = true; // [Optional arg, can be null or empty] [true|false] [default: true] [if true, expression will be reset to default after animation is over]
var crossOrigin = "anonymous"; // [Optional arg, to use not same-origin audios] [DEFAULT: null]
model.speak(audio_link, {volume: volume, expression:expression, resetExpression:resetExpression, crossOrigin: crossOrigin})
// Or if you want to keep some things default
model.speak(audio_link)
model.speak(audio_link, {volume: volume})
model.speak(audio_link, {expression:expression, resetExpression:resetExpression})
}
function draggable(model) {
model.buttonMode = true;
model.on("pointerdown", (e) => {
model.dragging = true;
model._pointerX = e.data.global.x - model.x;
model._pointerY = e.data.global.y - model.y;
});
model.on("pointermove", (e) => {
if (model.dragging) {
model.position.x = e.data.global.x - model._pointerX;
model.position.y = e.data.global.y - model._pointerY;
}
});
model.on("pointerupoutside", () => (model.dragging = false));
model.on("pointerup", () => (model.dragging = false));
}
function addFrame(model) {
const foreground = PIXI.Sprite.from(PIXI.Texture.WHITE);
foreground.width = model.internalModel.width;
foreground.height = model.internalModel.height;
foreground.alpha = 0.2;
model.addChild(foreground);
checkbox("Model Frames", (checked) => (foreground.visible = checked));
}
// function addHitAreaFrames(model) {
// const hitAreaFrames = new live2d.HitAreaFrames();
// hitAreaFrames.visible = true;
// model.addChild(hitAreaFrames);
// //checkbox("Hit Area Frames", (checked) => (hitAreaFrames.visible = checked));
// }
function checkbox(name, onChange) {
const id = name.replace(/\W/g, "").toLowerCase();
let checkbox = document.getElementById(id);
if (!checkbox) {
const p = document.createElement("p");
p.innerHTML = `<input type="checkbox" id="${id}"> <label for="${id}">${name}</label>`;
document.getElementById("control").appendChild(p);
checkbox = p.firstChild;
}
checkbox.addEventListener("change", () => {
onChange(checkbox.checked);
});
onChange(checkbox.checked);
}
</script>
<style>
#control{
position: absolute;
top:50px;
left: 50px;
color: white;
font-size:18px;
}
</style>
</body>
</html>