tts / main.ts
gnilets's picture
Update main.ts
726bf86 verified
raw
history blame
11.6 kB
import { serve } from "https://deno.land/std/http/server.ts";
import { EdgeSpeechTTS } from "https://esm.sh/@lobehub/tts@1";
const VOICES_URL = "https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list?trustedclienttoken=6A5AA1D4EAFF4E9FB37E23D68491D6F4";
async function fetchVoiceList() {
const response = await fetch(VOICES_URL);
const voices = await response.json();
return voices.reduce((acc: Record<string, { model: string, name: string, friendlyName: string, locale: string }[]>, voice: any) => {
const { ShortName: model, ShortName: name, FriendlyName: friendlyName, Locale: locale } = voice;
if (!acc[locale]) acc[locale] = [];
acc[locale].push({ model, name, friendlyName, locale });
return acc;
}, {});
}
async function handleDemoRequest(req: Request) {
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>tts</title>
</head>
<body>
<div class="container">
<div class="input-area">
<div class="slider-container">
<label for="rate">скорость:</label
><input
type="range"
min="-1"
max="1"
step="0.1"
value="-0.1"
class="slider"
id="rate"
/>
<div class="slider-value" id="rateValue">-0.1</div>
<label for="pitch">тон:</label
><input
type="range"
min="-1"
max="1"
step="0.1"
value="0.1"
class="slider"
id="pitch"
/>
<div class="slider-value" id="pitchValue">0.1</div>
</div>
<div class="textarea-container">
<label for="inputText">текст:</label
><textarea id="inputText">Привет, хочешь я расскажу сказку?</textarea>
</div>
<div class="dropdown-container">
<label for="voiceSelect">выберите голос:</label>
<select id="voiceSelect">
<option value="ava">ava</option>
<option value="andrew">andrew</option>
<option value="emma">emma</option>
<option value="brian">brian</option>
<option value="vivienne">vivienne</option>
<option value="remy">remy</option>
<option value="seraphina">seraphina</option>
<option value="florian">florian</option>
<option value="dmitry">dmitry</option>
<option value="svetlana">svetlana</option>
</select>
</div>
<button id="synthesizeButton">Синтезировать</button>
</div>
<div class="output-area">
<h1>Результат</h1>
<div id="audioPlayerContainer"></div>
</div>
</div>
<script>
let audio = null;
document.getElementById('synthesizeButton').addEventListener('click', () => {
const text = document.getElementById('inputText').value || 'Hello world';
const rate = document.getElementById('rate').value || '-0.1';
const pitch = document.getElementById('pitch').value || '0.1';
const voice = \`rate:\${rate}|pitch:\${pitch}\`;
const model = document.getElementById('voiceSelect').value;
if (audio) {
audio.pause();
audio.currentTime = 0;
}
fetch('/v1/audio/speech', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model, input: text, voice })
})
.then(response => response.blob())
.then(blob => {
const audioUrl = URL.createObjectURL(blob);
const audioPlayerContainer = document.getElementById('audioPlayerContainer');
if (audio) {
audio.src = audioUrl;
} else {
audio = new Audio(audioUrl);
audioPlayerContainer.appendChild(audio);
}
audio.play();
});
});
const rateSlider = document.getElementById('rate');
const rateValue = document.getElementById('rateValue');
rateSlider.oninput = function() {
rateValue.innerHTML = this.value;
};
const pitchSlider = document.getElementById('pitch');
const pitchValue = document.getElementById('pitchValue');
pitchSlider.oninput = function() {
pitchValue.innerHTML = this.value;
};
</script>
</body></html>`;
return new Response(html, {
headers: { "Content-Type": "text/html" },
});
}
function validateContentType(req: Request, expected: string) {
const contentType = req.headers.get("Content-Type");
if (contentType !== expected) {
console.log(`Invalid Content-Type ${contentType}, expected ${expected}`);
return new Response("Bad Request", { status: 400 });
}
}
async function handleDebugRequest(req: Request) {
const url = new URL(req.url);
const voice = url.searchParams.get("voice") || "";
const model = url.searchParams.get("model") || "";
const text = url.searchParams.get("text") || "";
console.log(`Debug request with model=${model}, voice=${voice}, text=${text}`);
if (!voice || !model || !text) {
console.log("Missing required parameters");
return new Response("Bad Request", { status: 400 });
}
return synthesizeSpeech(model, voice, text);
}
async function handleSynthesisRequest(req: Request) {
if (req.method !== "POST") {
console.log(`Invalid method ${req.method}, expected POST`);
return new Response("Method Not Allowed", { status: 405 });
}
const invalidContentType = validateContentType(req, "application/json");
if (invalidContentType) return invalidContentType;
const { model, input, voice } = await req.json();
console.log(`Synthesis request with model=${model}, input=${input}, voice=${voice}`);
return synthesizeSpeech(model, voice, input);
}
async function handleDemoRequest(req: Request) {
const groupedVoiceList = await fetchVoiceList();
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>tts</title>
</head>
<body>
<div class="container">
<div class="input-area">
<div class="filter-section">
<label for="keywords">фильтр по языкам:</label
><input type="text" id="keywords" value="multilingual,-RU" />
</div>
<div class="slider-container">
<label for="rate">скорость:</label
><input
type="range"
min="-1"
max="1"
step="0.1"
value="-0.1"
class="slider"
id="rate"
/>
<div class="slider-value" id="rateValue">-0.1</div>
<label for="pitch">тон:</label
><input
type="range"
min="-1"
max="1"
step="0.1"
value="0.1"
class="slider"
id="pitch"
/>
<div class="slider-value" id="pitchValue">0.1</div>
</div>
<div class="textarea-container">
<label for="inputText">текст:</label
><textarea id="inputText">Привет, хочешь я расскажу сказку?</textarea>
</div>
</div>
<div class="output-area">
<h1>голос</h1>
<div id="voices"></div>
</div>
</div>
<script>const voiceList = ${JSON.stringify(groupedVoiceList)};let audio=null;function filterVoices(){const keywords=document.getElementById('keywords').value.split(',').map(k=>k.trim().toLowerCase());const voicesDiv=document.getElementById('voices');voicesDiv.innerHTML='';const filteredVoices={};for(const[locale,voices]of Object.entries(voiceList)){const filtered=voices.filter(({name,friendlyName})=>keywords.some(keyword=>name.toLowerCase().includes(keyword)||friendlyName.toLowerCase().includes(keyword)));if(filtered.length>0){filteredVoices[locale]=filtered}}for(const[locale,voices]of Object.entries(filteredVoices)){const group=document.createElement('div');group.className='voice-group';group.draggable=true;const header=document.createElement('div');header.className='voice-header';header.textContent=locale.toUpperCase();const chevron=document.createElement('span');chevron.className='chevron';chevron.innerHTML='&#9660;';header.appendChild(chevron);const buttonsContainer=document.createElement('div');buttonsContainer.className='voice-buttons';voices.forEach(({model,name})=>{const button=document.createElement('button');button.className='voice-button';button.textContent=name;button.onclick=()=>synthesize(model);buttonsContainer.appendChild(button)});header.onclick=()=>{group.classList.toggle('open')};group.appendChild(header);group.appendChild(buttonsContainer);voicesDiv.appendChild(group)}addDragDropListeners()}function synthesize(model){const text=document.getElementById('inputText').value||'Hello world';const rate=document.getElementById('rate').value||'-0.1';const pitch=document.getElementById('pitch').value||'0.1';const voice=\`rate:\${rate}|pitch:\${pitch}\`;if(audio){audio.pause();audio.currentTime=0}fetch('/v1/audio/speech',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({model,input:text,voice})}).then(response=>response.blob()).then(blob=>{const audioUrl=URL.createObjectURL(blob);audio=new Audio(audioUrl);audio.play()})}function addDragDropListeners(){const voicesDiv=document.getElementById('voices');let draggedItem=null;voicesDiv.addEventListener('dragstart',e=>{draggedItem=e.target;e.target.classList.add('dragging')});voicesDiv.addEventListener('dragend',e=>{e.target.classList.remove('dragging');draggedItem=null});voicesDiv.addEventListener('dragover',e=>{e.preventDefault();const afterElement=getDragAfterElement(voicesDiv,e.clientY);if(afterElement==null){voicesDiv.appendChild(draggedItem)}else{voicesDiv.insertBefore(draggedItem,afterElement)}})}function getDragAfterElement(container,y){const draggableElements=[...container.querySelectorAll('.voice-group:not(.dragging)')];return draggableElements.reduce((closest,child)=>{const box=child.getBoundingClientRect();const offset=y-box.top-box.height/2;if(offset<0&&offset>closest.offset){return{offset:offset,element:child}}else{return closest}},{offset:Number.NEGATIVE_INFINITY}).element}filterVoices();document.getElementById('keywords').addEventListener('input',filterVoices);const rateSlider=document.getElementById('rate');const rateValue=document.getElementById('rateValue');rateSlider.oninput=function(){rateValue.innerHTML=this.value};const pitchSlider=document.getElementById('pitch');const pitchValue=document.getElementById('pitchValue');pitchSlider.oninput=function(){pitchValue.innerHTML=this.value}</script>
</body></html>`;
return new Response(html, {
headers: { "Content-Type": "text/html" },
});
}
serve(async (req) => {
try {
const url = new URL(req.url);
if (url.pathname === "/") {
return handleDemoRequest(req);
}
if (url.pathname === "/tts") {
return handleDebugRequest(req);
}
if (url.pathname !== "/v1/audio/speech") {
console.log(`Unhandled path ${url.pathname}`);
return new Response("Not Found", { status: 404 });
}
return handleSynthesisRequest(req);
} catch (err) {
console.error(`Error processing request: ${err.message}`);
return new Response(`Internal Server Error\n${err.message}`, {
status: 500,
});
}
});