Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 20,707 Bytes
7c0c96e 59366a8 7c0c96e 59366a8 7c0c96e | 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 | /* Voice embeddings visualiser, adapted from xVASynth javascript/embeddings.js.
The default layout uses the 3D coordinates exported by the xVASynth app
(allData.json). PCA and tSNE instead reduce the stored speaker vectors of
the downloaded voices in the page. */
(function () {
"use strict";
var SPHERE_RADIUS = 3;
var NEED_THREE = "You need at least 3 voices to run dimensionality reduction for the plot";
var state = {
voices: [],
byId: {},
games: [],
gameTitles: {},
gameColours: {},
voiceChecked: {},
data: {},
gendersOn: false,
ready: false,
looping: false,
clicked: null,
hoveredId: null,
scene: null
};
function $(id) {
return document.getElementById(id);
}
function showNotice(text) {
$("embeddingsNoticeText").textContent = text;
$("embeddingsNotice").hidden = false;
}
function hideNotice() {
$("embeddingsNotice").hidden = true;
}
function componentToHex(channel) {
var hex = Math.max(0, Math.min(255, channel | 0)).toString(16);
return hex.length === 1 ? "0" + hex : hex;
}
function rgbToHex(red, green, blue) {
return "#" + componentToHex(red) + componentToHex(green) + componentToHex(blue);
}
function hexToRgb(hex) {
var match = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex || "");
if (!match) {
return {r: 170, g: 170, b: 170};
}
return {
r: parseInt(match[1], 16),
g: parseInt(match[2], 16),
b: parseInt(match[3], 16)
};
}
function enabledGameIds() {
var ids = {};
Array.prototype.forEach.call($("embeddingsGamesListContainer").querySelectorAll("input"), function (box) {
if (box.checked) {
ids[box.id.replace(/^embs_/, "")] = true;
}
});
return ids;
}
function genderAllowed(gender) {
if (gender === "male") {
return $("embeddingsMalesCkbx").checked;
}
if (gender === "female") {
return $("embeddingsFemalesCkbx").checked;
}
return $("embeddingsOtherGendersCkbx").checked;
}
function voicesForReduction() {
var games = enabledGameIds();
var onlyInstalled = $("embeddingsOnlyInstalledCkbx").checked;
return state.voices.filter(function (voice) {
if (!games[voice.gameId]) {
return false;
}
if (state.voiceChecked[voice.voiceId] === false) {
return false;
}
if (!genderAllowed(voice.gender)) {
return false;
}
if (onlyInstalled && !voice.hasPreview) {
return false;
}
return true;
});
}
function paintPoint(point, brighten) {
var colour = state.gendersOn ? point.data.genderColour : point.data.gameColour;
var gain = brighten ? 1.5 : 1;
point.material.color.r = Math.min(1, colour.r / 255 * gain);
point.material.color.g = Math.min(1, colour.g / 255 * gain);
point.material.color.b = Math.min(1, colour.b / 255 * gain);
}
function clearSelection() {
if (state.clicked && state.clicked.object) {
state.clicked.object.material.emissive.setRGB(0, 0, 0);
}
state.clicked = null;
$("embeddingsVoiceNameDisplay").textContent = "";
$("embeddingsVoiceGenderDisplay").textContent = "";
$("embeddingsVoiceGameDisplay").textContent = "";
}
function selectPoint(point) {
if (state.clicked && state.clicked.object && state.clicked.object !== point) {
state.clicked.object.material.emissive.setRGB(0, 0, 0);
}
state.clicked = {
voiceId: point.data.voiceId,
object: point
};
point.material.emissive.setRGB(0, 1, 0);
var voice = state.byId[point.data.voiceId];
$("embeddingsVoiceNameDisplay").textContent = voice ? voice.voiceName : point.data.voiceId;
$("embeddingsVoiceGenderDisplay").textContent = voice ? voice.gender : "";
$("embeddingsVoiceGameDisplay").textContent = state.gameTitles[point.data.game] || point.data.game;
}
function populateVoicesList() {
var games = enabledGameIds();
var query = $("embeddingsSearchBar").value.toLowerCase().trim();
var container = $("embeddingsRecordsContainer");
container.innerHTML = "";
state.voices.forEach(function (voice) {
if (!games[voice.gameId]) {
return;
}
var row = document.createElement("div");
row.className = "voice-row";
var box = document.createElement("input");
box.type = "checkbox";
box.id = "embsVoice_" + voice.voiceId;
box.checked = state.voiceChecked[voice.voiceId] !== false;
box.addEventListener("click", function () {
state.voiceChecked[voice.voiceId] = box.checked;
recompute();
});
var show = document.createElement("button");
show.type = "button";
show.className = "smallButton";
show.textContent = "Show";
show.style.background = "#" + (state.gameColours[voice.gameId] || "aaaaaa");
show.addEventListener("click", function () {
showVoice(voice.voiceId, box.checked);
});
var name = document.createElement("div");
name.className = "ellipsis";
name.textContent = voice.voiceName;
name.title = voice.voiceName;
var game = document.createElement("div");
game.className = "ellipsis";
game.textContent = state.gameTitles[voice.gameId] || voice.gameId;
var gender = document.createElement("div");
gender.textContent = voice.gender;
var boxCell = document.createElement("div");
boxCell.appendChild(box);
var showCell = document.createElement("div");
showCell.appendChild(show);
row.appendChild(boxCell);
row.appendChild(showCell);
row.appendChild(name);
row.appendChild(game);
row.appendChild(gender);
// Search only hides rows. Checked voices stay in the next reduction, as in embeddings.js.
if (query && voice.voiceName.toLowerCase().trim().indexOf(query) === -1) {
return;
}
container.appendChild(row);
});
}
function populateGamesList() {
var container = $("embeddingsGamesListContainer");
container.innerHTML = "";
state.games.forEach(function (game) {
var button = document.createElement("button");
button.type = "button";
button.className = "game-button";
button.style.setProperty("background-color", "#" + game.colour, "important");
var box = document.createElement("input");
box.type = "checkbox";
box.id = "embs_" + game.id;
box.checked = true;
var label = document.createElement("span");
label.textContent = game.title;
button.appendChild(box);
button.appendChild(label);
button.addEventListener("click", function (event) {
if (event.target === box) {
return;
}
box.checked = !box.checked;
populateVoicesList();
recompute();
});
button.addEventListener("contextmenu", function (event) {
event.preventDefault();
Array.prototype.forEach.call(container.querySelectorAll("input"), function (other) {
other.checked = false;
});
box.checked = true;
populateVoicesList();
recompute();
});
box.addEventListener("click", function (event) {
event.stopPropagation();
populateVoicesList();
recompute();
});
container.appendChild(button);
});
}
function showVoice(voiceId, enabled) {
if (!enabled) {
showNotice("This voice is not enabled");
return;
}
var scene = state.scene;
if (!scene) {
return;
}
var point = null;
scene.points.forEach(function (candidate) {
if (candidate.data.voiceId === voiceId) {
point = candidate;
}
});
if (!point) {
showNotice("This voice is not in the current plot");
return;
}
var camera = scene.camera;
scene.controls.target.set(point.position.x, point.position.y, point.position.z);
camera.position.set(
camera.position.x + (point.position.x - camera.position.x) / 2,
camera.position.y + (point.position.y - camera.position.y) / 2,
camera.position.z + (point.position.z - camera.position.z) / 2
);
}
function refreshPoints() {
var scene = state.scene;
var data = state.data;
var kept = {};
var nextPoints = [];
var nextSprites = [];
scene.points.concat(scene.sprites).forEach(function (object) {
var voiceId = object.data.voiceId;
var coords = data[voiceId];
if (!coords) {
scene.three.remove(object);
if (object.dispose) {
object.dispose();
} else if (object.geometry) {
object.geometry.dispose();
if (object.material) {
object.material.dispose();
}
}
return;
}
kept[voiceId] = true;
object.data.isMoving = true;
object.data.newPos = {
x: coords[0],
y: coords[1] - (object.data.type === "text" ? SPHERE_RADIUS * 1.5 : 0),
z: coords[2]
};
if (object.data.type === "text") {
nextSprites.push(object);
} else {
nextPoints.push(object);
paintPoint(object, state.hoveredId === voiceId);
}
});
scene.points = nextPoints;
scene.sprites = nextSprites;
Object.keys(data).forEach(function (voiceId) {
if (kept[voiceId]) {
return;
}
var voice = state.byId[voiceId];
var gameId = voice ? voice.gameId : "other";
var gender = voice ? voice.gender : "other";
var gameRgb = hexToRgb(state.gameColours[gameId]);
var genderRgb = gender === "female"
? {r: 200, g: 0, b: 0}
: (gender === "male" ? {r: 0, g: 0, b: 200} : {r: 85, g: 85, b: 85});
var geometry = new THREE.SphereGeometry(SPHERE_RADIUS, 50, 50);
var material = new THREE.MeshLambertMaterial({
color: state.gendersOn ? rgbToHex(genderRgb.r, genderRgb.g, genderRgb.b) : "#" + (state.gameColours[gameId] || "aaaaaa"),
transparent: true
});
var point = new THREE.Mesh(geometry, material);
point.position.set(data[voiceId][0], data[voiceId][1], data[voiceId][2]);
point.data = {
type: "point",
voiceId: voiceId,
game: gameId,
gameColour: gameRgb,
genderColour: genderRgb
};
scene.points.push(point);
scene.three.add(point);
var sprite = new THREE.TextSprite({
text: voice ? voice.voiceName : voiceId,
fontFamily: "Helvetica, sans-serif",
fontSize: 2,
strokeColor: "#ffffff",
strokeWidth: 0,
color: "#24ff00",
material: {color: "white"}
});
sprite.position.set(data[voiceId][0], data[voiceId][1] - SPHERE_RADIUS * 1.5, data[voiceId][2]);
sprite.data = {type: "text", voiceId: voiceId, game: gameId};
scene.sprites.push(sprite);
scene.three.add(sprite);
});
if (state.clicked && !data[state.clicked.voiceId]) {
clearSelection();
} else if (state.clicked) {
scene.points.forEach(function (point) {
if (point.data.voiceId === state.clicked.voiceId) {
state.clicked.object = point;
point.material.emissive.setRGB(0, 1, 0);
}
});
}
}
function recompute() {
var voices = voicesForReduction();
if (voices.length <= 2) {
showNotice(NEED_THREE);
return;
}
var algorithm = $("embeddingsAlgorithm").value.split("_")[1];
if (algorithm === "xvasynth") {
var placed = {};
voices.forEach(function (voice) {
if (voice.coords) {
placed[voice.voiceId] = voice.coords;
}
});
state.data = placed;
if (state.scene) {
refreshPoints();
}
hideNotice();
return;
}
voices = voices.filter(function (voice) {
return voice.embedding;
});
if (voices.length <= 2) {
showNotice(NEED_THREE);
return;
}
var rows = voices.map(function (voice) {
return voice.embedding;
});
showNotice("Re-computing embeddings and dimensionality reduction on voices. May take a minute the first time, subsequent runs should be instant.");
window.setTimeout(function () {
try {
var coords = window.xvaReduce.project(rows, algorithm);
var data = {};
voices.forEach(function (voice, index) {
data[voice.voiceId] = coords[index];
});
state.data = data;
if (state.scene) {
refreshPoints();
}
hideNotice();
} catch (error) {
console.error(error);
showNotice(NEED_THREE);
}
}, 30);
}
function updateSize() {
var scene = state.scene;
var container = $("embeddingsSceneContainer");
if (!scene || container.clientWidth < 2 || container.clientHeight < 2) {
return;
}
scene.camera.aspect = container.clientWidth / container.clientHeight;
scene.camera.updateProjectionMatrix();
scene.renderer.setSize(container.clientWidth, container.clientHeight);
}
function step() {
var scene = state.scene;
var controls = scene.controls;
controls.update();
scene.controls2.target.set(controls.target.x, controls.target.y, controls.target.z);
scene.controls2.update();
scene.camera.updateMatrixWorld();
scene.points.concat(scene.sprites).forEach(function (object) {
if (!object.data.isMoving || !object.data.newPos) {
return;
}
var next = object.data.newPos;
if (Math.abs(object.position.x - next.x) > 0.005 || Math.abs(object.position.y - next.y) > 0.005 || Math.abs(object.position.z - next.z) > 0.005) {
object.position.x += (next.x - object.position.x) / 20;
object.position.y += (next.y - object.position.y) / 20;
object.position.z += (next.z - object.position.z) / 20;
} else {
object.data.isMoving = false;
object.data.newPos = null;
}
});
scene.raycaster.setFromCamera(scene.mouse, scene.camera);
var hits = scene.raycaster.intersectObjects(scene.points, false);
var hit = hits.length ? hits[0] : null;
if (hit && hit.object && hit.object.data && hit.object.data.type === "point") {
scene.renderer.domElement.style.cursor = "pointer";
if (state.hoveredId && state.hoveredId !== hit.object.data.voiceId) {
scene.points.forEach(function (point) {
if (point.data.voiceId === state.hoveredId) {
paintPoint(point, false);
}
});
}
state.hoveredId = hit.object.data.voiceId;
paintPoint(hit.object, true);
} else {
scene.renderer.domElement.style.cursor = "default";
if (state.hoveredId) {
scene.points.forEach(function (point) {
if (point.data.voiceId === state.hoveredId) {
paintPoint(point, false);
}
});
state.hoveredId = null;
}
}
scene.renderer.render(scene.three, scene.camera);
}
function ensureLoop() {
if (!state.ready || state.looping) {
return;
}
var container = $("embeddingsSceneContainer");
if (document.hidden || container.clientWidth < 2 || container.clientHeight < 2) {
return;
}
state.looping = true;
var tick = function () {
if (!state.looping) {
return;
}
if (document.hidden || container.clientWidth < 2 || container.clientHeight < 2) {
state.looping = false;
return;
}
requestAnimationFrame(tick);
step();
};
requestAnimationFrame(tick);
}
function initScene() {
var container = $("embeddingsSceneContainer");
var renderer = new THREE.WebGLRenderer({alpha: true, antialias: true});
renderer.setPixelRatio(window.devicePixelRatio || 1);
renderer.setSize(Math.max(container.clientWidth, 2), Math.max(container.clientHeight, 2));
container.appendChild(renderer.domElement);
var threeScene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, container.clientWidth / Math.max(container.clientHeight, 1), 0.001, 100000);
camera.position.set(-100, 0, 0);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
var controls2 = new THREE.TrackballControls(camera, renderer.domElement);
controls.target.set(camera.position.x + 0.15, camera.position.y, camera.position.z);
controls.enableDamping = true;
controls.dampingFactor = 0.025;
controls.screenSpacePanning = true;
controls.rotateSpeed = 1 / 6;
controls.panSpeed = 1;
controls.minDistance = 50;
controls.maxDistance = 500;
controls2.noRotate = true;
controls2.noPan = true;
controls2.noZoom = true;
controls2.zoomSpeed = 1 / 2;
controls2.dynamicDampingFactor = 0.2;
var light = new THREE.DirectionalLight(0xffffff, 0.5);
light.position.set(-1, 1, 1).normalize();
threeScene.add(light);
threeScene.add(new THREE.AmbientLight(0xffffff, 0.5));
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
renderer.domElement.addEventListener("mousemove", function (event) {
var rect = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
});
var pointerDown = null;
function pointerRay(event) {
var rect = renderer.domElement.getBoundingClientRect();
if (rect.width < 1 || rect.height < 1) {
return null;
}
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var hits = raycaster.intersectObjects(state.scene.points, false);
return hits.length ? hits[0].object : null;
}
renderer.domElement.addEventListener("mousedown", function (event) {
pointerDown = {x: event.clientX, y: event.clientY, button: event.button};
});
window.addEventListener("mouseup", function (event) {
if (!pointerDown || event.button !== pointerDown.button) {
return;
}
var smallMove = Math.abs(event.clientX - pointerDown.x) < 10 && Math.abs(event.clientY - pointerDown.y) < 10;
var button = pointerDown.button;
pointerDown = null;
if (!smallMove) {
return;
}
var object = pointerRay(event);
if (object && object.data && object.data.type === "point") {
if (button === 2) {
playPreview(state.byId[object.data.voiceId]);
} else if (button === 0) {
selectPoint(object);
}
} else if (button === 0) {
clearSelection();
}
});
renderer.domElement.addEventListener("contextmenu", function (event) {
event.preventDefault();
});
state.scene = {
three: threeScene,
camera: camera,
renderer: renderer,
controls: controls,
controls2: controls2,
raycaster: raycaster,
mouse: mouse,
points: [],
sprites: []
};
state.ready = true;
updateSize();
refreshPoints();
ensureLoop();
if (typeof ResizeObserver !== "undefined") {
var observer = new ResizeObserver(function () {
updateSize();
ensureLoop();
});
observer.observe(container);
}
document.addEventListener("visibilitychange", ensureLoop);
window.addEventListener("resize", function () {
updateSize();
ensureLoop();
});
}
function playPreview(voice) {
if (!voice) {
showNotice("Select a voice from the scene below first.");
return;
}
if (!voice.hasPreview) {
showNotice("No preview audio file available");
return;
}
var audio = $("embeddingsPreviewAudio");
audio.src = "preview/" + encodeURIComponent(voice.voiceId);
var played = audio.play();
if (played && played.catch) {
played.catch(function () {
showNotice("No preview audio file available");
});
}
}
function loadVoice() {
if (!state.clicked) {
showNotice("Select a voice from the scene below first.");
return;
}
var voice = state.byId[state.clicked.voiceId];
if (!voice || !voice.inSynth) {
showNotice("This voice is not in the synthesizer list.");
return;
}
window.parent.postMessage({type: "xvasynth-load-voice", voiceId: voice.voiceId}, window.location.origin);
}
function bindChrome() {
$("embeddingsNoticeClose").addEventListener("click", hideNotice);
$("embeddingsCloseHelpUI").addEventListener("click", function () {
$("embeddingsHelpUI").hidden = true;
});
$("embeddingsSearchBar").addEventListener("keyup", populateVoicesList);
$("embeddingsPreviewButton").addEventListener("click", function () {
playPreview(state.clicked ? state.byId[state.clicked.voiceId] : null);
});
$("embeddingsLoadButton").addEventListener("click", loadVoice);
$("embeddingsKey").addEventListener("change", function () {
state.gendersOn = $("embeddingsKey").value === "embsKey_gender";
if (state.scene) {
state.scene.points.forEach(function (point) {
paintPoint(point, state.hoveredId === point.data.voiceId);
});
}
});
["embeddingsMalesCkbx", "embeddingsFemalesCkbx", "embeddingsOtherGendersCkbx", "embeddingsOnlyInstalledCkbx", "embeddingsAlgorithm"].forEach(function (id) {
$(id).addEventListener("change", recompute);
});
}
function start(payload) {
state.games = payload.games || [];
state.voices = payload.voices || [];
state.games.forEach(function (game) {
state.gameTitles[game.id] = game.title;
state.gameColours[game.id] = game.colour;
});
state.voices.forEach(function (voice) {
state.byId[voice.voiceId] = voice;
state.voiceChecked[voice.voiceId] = true;
});
populateGamesList();
populateVoicesList();
initScene();
recompute();
}
bindChrome();
if (!window.THREE || !window.xvaReduce) {
showNotice("The embeddings view could not load its 3D libraries.");
return;
}
fetch("data.json").then(function (response) {
if (!response.ok) {
throw new Error("data.json " + response.status);
}
return response.json();
}).then(start).catch(function (error) {
console.error(error);
showNotice("Could not load voice embeddings.");
});
})();
|