Audio.svelte 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { createEventDispatcher, onMount, getContext } from 'svelte';
  4. import { KokoroTTS } from 'kokoro-js';
  5. import { user, settings, config } from '$lib/stores';
  6. import { getVoices as _getVoices } from '$lib/apis/audio';
  7. import Switch from '$lib/components/common/Switch.svelte';
  8. import { round } from '@huggingface/transformers';
  9. import Spinner from '$lib/components/common/Spinner.svelte';
  10. const dispatch = createEventDispatcher();
  11. const i18n = getContext('i18n');
  12. export let saveSettings: Function;
  13. // Audio
  14. let conversationMode = false;
  15. let speechAutoSend = false;
  16. let responseAutoPlayback = false;
  17. let nonLocalVoices = false;
  18. let STTEngine = '';
  19. let TTSEngine = '';
  20. let TTSEngineConfig = {};
  21. let TTSModel = null;
  22. let TTSModelProgress = null;
  23. let TTSModelLoading = false;
  24. let voices = [];
  25. let voice = '';
  26. // Audio speed control
  27. let playbackRate = 1;
  28. const speedOptions = [2, 1.75, 1.5, 1.25, 1, 0.75, 0.5];
  29. const getVoices = async () => {
  30. if (TTSEngine === 'browser-kokoro') {
  31. if (!TTSModel) {
  32. await loadKokoro();
  33. }
  34. voices = Object.entries(TTSModel.voices).map(([key, value]) => {
  35. return {
  36. id: key,
  37. name: value.name,
  38. localService: false
  39. };
  40. });
  41. } else {
  42. if ($config.audio.tts.engine === '') {
  43. const getVoicesLoop = setInterval(async () => {
  44. voices = await speechSynthesis.getVoices();
  45. // do your loop
  46. if (voices.length > 0) {
  47. clearInterval(getVoicesLoop);
  48. }
  49. }, 100);
  50. } else {
  51. const res = await _getVoices(localStorage.token).catch((e) => {
  52. toast.error(`${e}`);
  53. });
  54. if (res) {
  55. console.log(res);
  56. voices = res.voices;
  57. }
  58. }
  59. }
  60. };
  61. const toggleResponseAutoPlayback = async () => {
  62. responseAutoPlayback = !responseAutoPlayback;
  63. saveSettings({ responseAutoPlayback: responseAutoPlayback });
  64. };
  65. const toggleSpeechAutoSend = async () => {
  66. speechAutoSend = !speechAutoSend;
  67. saveSettings({ speechAutoSend: speechAutoSend });
  68. };
  69. onMount(async () => {
  70. playbackRate = $settings.audio?.tts?.playbackRate ?? 1;
  71. conversationMode = $settings.conversationMode ?? false;
  72. speechAutoSend = $settings.speechAutoSend ?? false;
  73. responseAutoPlayback = $settings.responseAutoPlayback ?? false;
  74. STTEngine = $settings?.audio?.stt?.engine ?? '';
  75. TTSEngine = $settings?.audio?.tts?.engine ?? '';
  76. TTSEngineConfig = $settings?.audio?.tts?.engineConfig ?? {};
  77. if ($settings?.audio?.tts?.defaultVoice === $config.audio.tts.voice) {
  78. voice = $settings?.audio?.tts?.voice ?? $config.audio.tts.voice ?? '';
  79. } else {
  80. voice = $config.audio.tts.voice ?? '';
  81. }
  82. nonLocalVoices = $settings.audio?.tts?.nonLocalVoices ?? false;
  83. await getVoices();
  84. });
  85. $: if (TTSEngine && TTSEngineConfig) {
  86. onTTSEngineChange();
  87. }
  88. const onTTSEngineChange = async () => {
  89. if (TTSEngine === 'browser-kokoro') {
  90. await loadKokoro();
  91. }
  92. };
  93. const loadKokoro = async () => {
  94. if (TTSEngine === 'browser-kokoro') {
  95. voices = [];
  96. if (TTSEngineConfig?.dtype) {
  97. TTSModel = null;
  98. TTSModelProgress = null;
  99. TTSModelLoading = true;
  100. const model_id = 'onnx-community/Kokoro-82M-v1.0-ONNX';
  101. TTSModel = await KokoroTTS.from_pretrained(model_id, {
  102. dtype: TTSEngineConfig.dtype, // Options: "fp32", "fp16", "q8", "q4", "q4f16"
  103. device: !!navigator?.gpu ? 'webgpu' : 'wasm', // Detect WebGPU
  104. progress_callback: (e) => {
  105. TTSModelProgress = e;
  106. console.log(e);
  107. }
  108. });
  109. await getVoices();
  110. // const rawAudio = await tts.generate(inputText, {
  111. // // Use `tts.list_voices()` to list all available voices
  112. // voice: voice
  113. // });
  114. // const blobUrl = URL.createObjectURL(await rawAudio.toBlob());
  115. // const audio = new Audio(blobUrl);
  116. // audio.play();
  117. }
  118. }
  119. };
  120. </script>
  121. <form
  122. class="flex flex-col h-full justify-between space-y-3 text-sm"
  123. on:submit|preventDefault={async () => {
  124. saveSettings({
  125. audio: {
  126. stt: {
  127. engine: STTEngine !== '' ? STTEngine : undefined
  128. },
  129. tts: {
  130. engine: TTSEngine !== '' ? TTSEngine : undefined,
  131. engineConfig: TTSEngineConfig,
  132. playbackRate: playbackRate,
  133. voice: voice !== '' ? voice : undefined,
  134. defaultVoice: $config?.audio?.tts?.voice ?? '',
  135. nonLocalVoices: $config.audio.tts.engine === '' ? nonLocalVoices : undefined
  136. }
  137. }
  138. });
  139. dispatch('save');
  140. }}
  141. >
  142. <div class=" space-y-3 overflow-y-scroll max-h-[28rem] lg:max-h-full">
  143. <div>
  144. <div class=" mb-1 text-sm font-medium">{$i18n.t('STT Settings')}</div>
  145. {#if $config.audio.stt.engine !== 'web'}
  146. <div class=" py-0.5 flex w-full justify-between">
  147. <div class=" self-center text-xs font-medium">{$i18n.t('Speech-to-Text Engine')}</div>
  148. <div class="flex items-center relative">
  149. <select
  150. class="dark:bg-gray-900 w-fit pr-8 rounded-sm px-2 p-1 text-xs bg-transparent outline-hidden text-right"
  151. bind:value={STTEngine}
  152. placeholder="Select an engine"
  153. >
  154. <option value="">{$i18n.t('Default')}</option>
  155. <option value="web">{$i18n.t('Web API')}</option>
  156. </select>
  157. </div>
  158. </div>
  159. {/if}
  160. <div class=" py-0.5 flex w-full justify-between">
  161. <div class=" self-center text-xs font-medium">
  162. {$i18n.t('Instant Auto-Send After Voice Transcription')}
  163. </div>
  164. <button
  165. class="p-1 px-3 text-xs flex rounded-sm transition"
  166. on:click={() => {
  167. toggleSpeechAutoSend();
  168. }}
  169. type="button"
  170. >
  171. {#if speechAutoSend === true}
  172. <span class="ml-2 self-center">{$i18n.t('On')}</span>
  173. {:else}
  174. <span class="ml-2 self-center">{$i18n.t('Off')}</span>
  175. {/if}
  176. </button>
  177. </div>
  178. </div>
  179. <div>
  180. <div class=" mb-1 text-sm font-medium">{$i18n.t('TTS Settings')}</div>
  181. <div class=" py-0.5 flex w-full justify-between">
  182. <div class=" self-center text-xs font-medium">{$i18n.t('Text-to-Speech Engine')}</div>
  183. <div class="flex items-center relative">
  184. <select
  185. class="dark:bg-gray-900 w-fit pr-8 rounded-sm px-2 p-1 text-xs bg-transparent outline-hidden text-right"
  186. bind:value={TTSEngine}
  187. placeholder="Select an engine"
  188. >
  189. <option value="">{$i18n.t('Default')}</option>
  190. <option value="browser-kokoro">{$i18n.t('Kokoro.js (Browser)')}</option>
  191. </select>
  192. </div>
  193. </div>
  194. {#if TTSEngine === 'browser-kokoro'}
  195. <div class=" py-0.5 flex w-full justify-between">
  196. <div class=" self-center text-xs font-medium">{$i18n.t('Kokoro.js Dtype')}</div>
  197. <div class="flex items-center relative">
  198. <select
  199. class="dark:bg-gray-900 w-fit pr-8 rounded-sm px-2 p-1 text-xs bg-transparent outline-hidden text-right"
  200. bind:value={TTSEngineConfig.dtype}
  201. placeholder="Select dtype"
  202. >
  203. <option value="" disabled selected>Select dtype</option>
  204. <option value="fp32">fp32</option>
  205. <option value="fp16">fp16</option>
  206. <option value="q8">q8</option>
  207. <option value="q4">q4</option>
  208. </select>
  209. </div>
  210. </div>
  211. {/if}
  212. <div class=" py-0.5 flex w-full justify-between">
  213. <div class=" self-center text-xs font-medium">{$i18n.t('Auto-playback response')}</div>
  214. <button
  215. class="p-1 px-3 text-xs flex rounded-sm transition"
  216. on:click={() => {
  217. toggleResponseAutoPlayback();
  218. }}
  219. type="button"
  220. >
  221. {#if responseAutoPlayback === true}
  222. <span class="ml-2 self-center">{$i18n.t('On')}</span>
  223. {:else}
  224. <span class="ml-2 self-center">{$i18n.t('Off')}</span>
  225. {/if}
  226. </button>
  227. </div>
  228. <div class=" py-0.5 flex w-full justify-between">
  229. <div class=" self-center text-xs font-medium">{$i18n.t('Speech Playback Speed')}</div>
  230. <div class="flex items-center relative">
  231. <select
  232. class="dark:bg-gray-900 w-fit pr-8 rounded-sm px-2 p-1 text-xs bg-transparent outline-hidden text-right"
  233. bind:value={playbackRate}
  234. >
  235. {#each speedOptions as option}
  236. <option value={option} selected={playbackRate === option}>{option}x</option>
  237. {/each}
  238. </select>
  239. </div>
  240. </div>
  241. </div>
  242. <hr class=" border-gray-100 dark:border-gray-850" />
  243. {#if TTSEngine === 'browser-kokoro'}
  244. {#if TTSModel}
  245. <div>
  246. <div class=" mb-2.5 text-sm font-medium">{$i18n.t('Set Voice')}</div>
  247. <div class="flex w-full">
  248. <div class="flex-1">
  249. <input
  250. list="voice-list"
  251. class="w-full rounded-lg py-2 px-4 text-sm bg-white dark:text-gray-300 dark:bg-gray-850 outline-hidden"
  252. bind:value={voice}
  253. placeholder="Select a voice"
  254. />
  255. <datalist id="voice-list">
  256. {#each voices as voice}
  257. <option value={voice.id}>{voice.name}</option>
  258. {/each}
  259. </datalist>
  260. </div>
  261. </div>
  262. </div>
  263. {:else}
  264. <div>
  265. <div class=" mb-2.5 text-sm font-medium flex gap-2 items-center">
  266. <Spinner className="size-4" />
  267. <div class=" text-sm font-medium shimmer">
  268. {$i18n.t('Loading Kokoro.js...')}
  269. {TTSModelProgress && TTSModelProgress.status === 'progress'
  270. ? `(${Math.round(TTSModelProgress.progress * 10) / 10}%)`
  271. : ''}
  272. </div>
  273. </div>
  274. <div class="text-xs text-gray-500">
  275. {$i18n.t('Please do not close the settings page while loading the model.')}
  276. </div>
  277. </div>
  278. {/if}
  279. {:else if $config.audio.tts.engine === ''}
  280. <div>
  281. <div class=" mb-2.5 text-sm font-medium">{$i18n.t('Set Voice')}</div>
  282. <div class="flex w-full">
  283. <div class="flex-1">
  284. <select
  285. class="w-full rounded-lg py-2 px-4 text-sm bg-white dark:text-gray-300 dark:bg-gray-850 outline-hidden"
  286. bind:value={voice}
  287. >
  288. <option value="" selected={voice !== ''}>{$i18n.t('Default')}</option>
  289. {#each voices.filter((v) => nonLocalVoices || v.localService === true) as _voice}
  290. <option
  291. value={_voice.name}
  292. class="bg-gray-100 dark:bg-gray-700"
  293. selected={voice === _voice.name}>{_voice.name}</option
  294. >
  295. {/each}
  296. </select>
  297. </div>
  298. </div>
  299. <div class="flex items-center justify-between my-1.5">
  300. <div class="text-xs">
  301. {$i18n.t('Allow non-local voices')}
  302. </div>
  303. <div class="mt-1">
  304. <Switch bind:state={nonLocalVoices} />
  305. </div>
  306. </div>
  307. </div>
  308. {:else if $config.audio.tts.engine !== ''}
  309. <div>
  310. <div class=" mb-2.5 text-sm font-medium">{$i18n.t('Set Voice')}</div>
  311. <div class="flex w-full">
  312. <div class="flex-1">
  313. <input
  314. list="voice-list"
  315. class="w-full rounded-lg py-2 px-4 text-sm bg-white dark:text-gray-300 dark:bg-gray-850 outline-hidden"
  316. bind:value={voice}
  317. placeholder="Select a voice"
  318. />
  319. <datalist id="voice-list">
  320. {#each voices as voice}
  321. <option value={voice.id}>{voice.name}</option>
  322. {/each}
  323. </datalist>
  324. </div>
  325. </div>
  326. </div>
  327. {/if}
  328. </div>
  329. <div class="flex justify-end text-sm font-medium">
  330. <button
  331. class="px-3.5 py-1.5 text-sm font-medium bg-black hover:bg-gray-900 text-white dark:bg-white dark:text-black dark:hover:bg-gray-100 transition rounded-full"
  332. type="submit"
  333. >
  334. {$i18n.t('Save')}
  335. </button>
  336. </div>
  337. </form>