-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTTSModule.cs
More file actions
2391 lines (2094 loc) · 106 KB
/
TTSModule.cs
File metadata and controls
2391 lines (2094 loc) · 106 KB
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using NetCord;
using NetCord.Gateway;
using NetCord.Gateway.Voice;
using NetCord.Rest;
using System;
using System.Threading.Tasks;
using System.Speech.Synthesis;
using System.Speech.AudioFormat;
using System.IO;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Configuration;
using System.Threading;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
namespace DiscordBotTTS
{
public class TTSModule
{
static ConcurrentDictionary<ulong, ValueTuple<VoiceClient, VoiceGuildChannel, Stream, SemaphoreSlim>> map = new ConcurrentDictionary<ulong, (VoiceClient, VoiceGuildChannel, Stream, SemaphoreSlim)>();
static Task dq;
static Task saver;
private RestClient _restClient;
public async Task UserInfoAsync(User user = null, TextChannel channel = null)
{
// This will need to be adapted for NetCord when we have proper context
// var userInfo = user ?? /* current user */;
// await channel.SendMessageAsync($"{userInfo.Username}");
}
private static void Log(string msg, string level = "Info")
{
Console.WriteLine($"{DateTime.Now.ToString("s")}:TTS:{level}: {msg}");
}
public void SetRestClient(RestClient restClient)
{
_restClient = restClient;
}
private static GatewayClient _gatewayClient; // Store gateway client for proper disconnection
private static HttpClient _httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) };
private static Process _coquiServerProcess;
private static bool _serverStarted = false;
private static readonly object _serverLock = new object();
// PocketTTS fields
private static Process _pocketServerProcess;
private static bool _pocketServerStarted = false;
private static readonly object _pocketServerLock = new object();
private static Dictionary<string, string> pocketVoiceModels = new Dictionary<string, string>();
private static readonly string[] PocketPredefinedVoices = { "alba", "marius", "javert", "jean", "fantine", "cosette", "eponine", "azelma" };
// Engine enable/disable switches
private static bool _enableSystemSpeech = true;
private static bool _enableCoquiTTS = true;
private static bool _enablePocketTTS = true;
private static bool _pocketLocalPaths = false;
public static void LoadEngineSwitch()
{
_enableSystemSpeech = bool.TryParse(ConfigurationManager.AppSettings.Get("EnableSystemSpeech"), out var es) ? es : true;
_enableCoquiTTS = bool.TryParse(ConfigurationManager.AppSettings.Get("EnableCoquiTTS"), out var ec) ? ec : true;
_enablePocketTTS = bool.TryParse(ConfigurationManager.AppSettings.Get("EnablePocketTTS"), out var ep) ? ep : true;
_pocketLocalPaths = bool.TryParse(ConfigurationManager.AppSettings.Get("PocketTTS_LocalPaths"), out var lp) ? lp : false;
Log($"Engine switches — SystemSpeech={_enableSystemSpeech}, CoquiTTS={_enableCoquiTTS}, PocketTTS={_enablePocketTTS}, PocketLocalPaths={_pocketLocalPaths}");
}
// Load Coqui voice configuration from app.config
private static void LoadCoquiVoiceConfiguration()
{
if (coquiVoiceModels.Count == 0) // Only load once
{
try
{
var coquiMode = ConfigurationManager.AppSettings.Get("CoquiMode")?.ToLower() ?? "exe";
if (coquiMode == "exe")
{
// Load voice model mappings for exe mode (legacy)
var modelsConfig = ConfigurationManager.AppSettings.Get("CoquiVoiceModels");
if (!string.IsNullOrEmpty(modelsConfig))
{
var pairs = modelsConfig.Split(';');
foreach (var pair in pairs)
{
var parts = pair.Split(':');
if (parts.Length == 2)
{
coquiVoiceModels[parts[0].Trim()] = parts[1].Trim();
}
}
}
Log($"Loaded {coquiVoiceModels.Count} Coqui voice models for exe mode");
}
// Server mode is now handled in InitializeCoquiServerAsync with parallel discovery
}
catch (Exception ex)
{
Log($"Error loading Coqui voice configuration: {ex.Message}", "Warning");
}
}
}
// Initialize Coqui TTS server on application startup
public static async Task InitializeCoquiServerAsync()
{
if (!_enableCoquiTTS)
{
Log("Coqui TTS engine disabled via config — skipping server startup");
return;
}
var coquiMode = ConfigurationManager.AppSettings.Get("CoquiMode")?.ToLower() ?? "exe";
if (coquiMode == "server")
{
Log("Initializing Coqui TTS server at startup...");
await EnsureCoquiServerStarted();
// Start speaker discovery in parallel with server startup
var speakerDiscoveryTask = Task.Run(async () => await DiscoverCoquiSpeakers());
// Wait for server to be ready with retry mechanism
await WaitForServerReady();
// Wait for speaker discovery to complete and load configuration
Log("Waiting for speaker discovery to complete...");
var discoveredSpeakers = await speakerDiscoveryTask;
// Load discovered speakers into voice models
foreach (var speaker in discoveredSpeakers)
{
coquiVoiceModels[$"CoQui_{speaker}"] = speaker;
}
Log($"Loaded {coquiVoiceModels.Count} Coqui speakers for server mode (discovered in parallel)");
}
else
{
Log("Coqui TTS server mode disabled - using exe mode");
}
}
// Discover available speakers for the loaded model
private static async Task<List<string>> DiscoverCoquiSpeakers()
{
var speakers = new List<string>();
try
{
var coquiPath = ConfigurationManager.AppSettings.Get("coquitts") ?? "tts";
var model = ConfigurationManager.AppSettings.Get("coqui_server_model") ?? "tts_models/en/ljspeech/tacotron2-DDC";
Log($"Discovering speakers for model: {model}");
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = coquiPath,
Arguments = $"--model_name {model} --list_speaker_idx",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
process.Start();
var output = await process.StandardOutput.ReadToEndAsync();
var error = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
if (!string.IsNullOrEmpty(error))
{
Log($"Speaker discovery stderr: {error}", "Warning");
// Extract speaker list from stderr (due to logging issue)
var match = Regex.Match(error, @"Message: \[([^\]]+)\]");
if (match.Success)
{
var speakerListText = match.Groups[1].Value;
var speakerMatches = Regex.Matches(speakerListText, @"'([^']+)'");
foreach (Match speakerMatch in speakerMatches)
{
var speakerName = speakerMatch.Groups[1].Value;
if (!string.IsNullOrEmpty(speakerName))
{
speakers.Add(speakerName);
}
}
}
}
if (!string.IsNullOrEmpty(output))
{
Log($"Speaker discovery output: {output}");
// Parse speaker list from output (fallback)
var lines = output.Split('\n', StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
var trimmed = line.Trim();
if (!string.IsNullOrEmpty(trimmed) &&
!trimmed.Contains("INFO") &&
!trimmed.Contains("WARNING") &&
!trimmed.Contains("ERROR") &&
!trimmed.Contains("Loading") &&
!trimmed.Contains("Setting up") &&
!trimmed.Contains("downloaded") &&
!trimmed.Contains("Using model"))
{
speakers.Add(trimmed);
}
}
}
Log($"Discovered {speakers.Count} speakers: {string.Join(", ", speakers)}");
}
catch (Exception ex)
{
Log($"Error discovering speakers: {ex.Message}", "Warning");
// Fallback to config if discovery fails
var fallbackConfig = ConfigurationManager.AppSettings.Get("CoquiSpeakers");
if (!string.IsNullOrEmpty(fallbackConfig))
{
speakers.AddRange(fallbackConfig.Split(',').Select(s => s.Trim()));
Log($"Using fallback speakers from config: {string.Join(", ", speakers)}");
}
}
return speakers;
}
// Wait for Coqui TTS server to be ready with retry mechanism
private static async Task WaitForServerReady()
{
var port = ConfigurationManager.AppSettings.Get("coqui_server_port") ?? "5002";
var startupTimeout = int.Parse(ConfigurationManager.AppSettings.Get("coqui_server_startup_timeout") ?? "60");
var retryInterval = int.Parse(ConfigurationManager.AppSettings.Get("coqui_server_retry_interval") ?? "2");
var maxRetries = startupTimeout / retryInterval;
var attempt = 0;
Log($"Waiting for Coqui TTS server to be ready (timeout: {startupTimeout}s, retry interval: {retryInterval}s)...");
while (attempt < maxRetries)
{
try
{
var response = await _httpClient.GetAsync($"http://localhost:{port}/");
if (response.IsSuccessStatusCode)
{
Log($"Coqui TTS server is ready! (took {attempt * retryInterval}s)");
return;
}
else
{
Log($"Server responded with status: {response.StatusCode}, retrying in {retryInterval}s... (attempt {attempt + 1}/{maxRetries})");
}
}
catch (Exception ex)
{
Log($"Server not ready yet: {ex.Message}, retrying in {retryInterval}s... (attempt {attempt + 1}/{maxRetries})");
}
attempt++;
if (attempt < maxRetries)
{
await Task.Delay(retryInterval * 1000);
}
}
Log($"Coqui TTS server did not become ready within {startupTimeout}s timeout", "Warning");
}
// Cleanup Coqui TTS server on application exit
public static void CleanupCoquiServer()
{
lock (_serverLock)
{
if (_coquiServerProcess != null && !_coquiServerProcess.HasExited)
{
try
{
Log("Shutting down Coqui TTS server (killing process tree)...");
_coquiServerProcess.Kill(entireProcessTree: true);
_coquiServerProcess.WaitForExit(5000);
Log("Coqui TTS server shutdown completed");
}
catch (Exception ex)
{
Log($"Error shutting down Coqui TTS server: {ex.Message}", "Warning");
}
finally
{
try { _coquiServerProcess.Dispose(); } catch { }
_coquiServerProcess = null;
_serverStarted = false;
}
}
}
}
// ==================== PocketTTS Engine ====================
// Initialize PocketTTS server on application startup
public static async Task InitializePocketTTSServerAsync()
{
if (!_enablePocketTTS)
{
Log("PocketTTS engine disabled via config — skipping server startup");
return;
}
Log("Initializing PocketTTS server at startup...");
// Ensure voice directory exists
var voiceDir = ConfigurationManager.AppSettings.Get("PocketTTS_VoiceDirectory") ?? "";
if (!string.IsNullOrEmpty(voiceDir))
{
try
{
Directory.CreateDirectory(voiceDir);
Log($"PocketTTS voice directory ensured: {voiceDir}");
}
catch (Exception ex)
{
Log($"Failed to create PocketTTS voice directory '{voiceDir}': {ex.Message}", "Warning");
}
}
await EnsurePocketServerStarted();
await WaitForPocketServerReady();
// Discover voices
DiscoverPocketVoices();
Log($"PocketTTS initialized with {pocketVoiceModels.Count} voices");
}
private static void DiscoverPocketVoices()
{
pocketVoiceModels.Clear();
// Register predefined voices
foreach (var v in PocketPredefinedVoices)
{
pocketVoiceModels[$"Pocket_{v}"] = v;
}
// Auto-discover custom voices from voice directory (.safetensors files)
var voiceDir = ConfigurationManager.AppSettings.Get("PocketTTS_VoiceDirectory") ?? "";
if (!string.IsNullOrEmpty(voiceDir) && Directory.Exists(voiceDir))
{
foreach (var file in Directory.GetFiles(voiceDir, "*.safetensors"))
{
var name = Path.GetFileNameWithoutExtension(file);
var key = $"Pocket_{name}";
if (!pocketVoiceModels.ContainsKey(key))
{
pocketVoiceModels[key] = file;
Log($"Auto-discovered PocketTTS custom voice: {key} → {file}");
}
}
}
// Load additional custom voice mappings from pocketvoices.json (HF URLs, non-standard paths, etc.)
LoadPocketVoicesJson();
Log($"PocketTTS voice discovery complete: {pocketVoiceModels.Count} voices ({PocketPredefinedVoices.Length} predefined + {pocketVoiceModels.Count - PocketPredefinedVoices.Length} custom)");
}
private static readonly string PocketVoicesJsonPath = "pocketvoices.json";
private static void LoadPocketVoicesJson()
{
try
{
if (File.Exists(PocketVoicesJsonPath))
{
var json = File.ReadAllText(PocketVoicesJsonPath);
if (!string.IsNullOrWhiteSpace(json) && json != "{}")
{
var entries = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
if (entries != null)
{
foreach (var kv in entries)
{
var key = kv.Key.StartsWith("Pocket_", StringComparison.OrdinalIgnoreCase)
? kv.Key
: $"Pocket_{kv.Key}";
if (!pocketVoiceModels.ContainsKey(key))
{
pocketVoiceModels[key] = kv.Value;
Log($"Loaded PocketTTS voice from pocketvoices.json: {key} → {kv.Value}");
}
}
Log($"Loaded {entries.Count} custom voice mappings from {PocketVoicesJsonPath}");
}
}
}
}
catch (Exception ex)
{
Log($"Error loading {PocketVoicesJsonPath}: {ex.Message}", "Warning");
}
}
private static void SavePocketVoicesJson()
{
try
{
// Build dict of only custom (non-predefined) voices
var customEntries = new Dictionary<string, string>();
foreach (var kv in pocketVoiceModels)
{
// Skip predefined voices — they're always auto-registered
if (PocketPredefinedVoices.Contains(kv.Value, StringComparer.OrdinalIgnoreCase))
continue;
customEntries[kv.Key] = kv.Value;
}
var json = JsonSerializer.Serialize(customEntries, new JsonSerializerOptions { WriteIndented = true });
// Guard: never write empty data
if (string.IsNullOrWhiteSpace(json) || json == "{}")
{
// If there are no custom voices, delete the file if it exists
if (File.Exists(PocketVoicesJsonPath))
{
File.Delete(PocketVoicesJsonPath);
Log("Removed empty pocketvoices.json (no custom voices)");
}
return;
}
// Atomic write with backup (same pattern as userprefs.json)
var tmpPath = PocketVoicesJsonPath + ".tmp";
File.WriteAllText(tmpPath, json);
if (File.Exists(PocketVoicesJsonPath))
{
var timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
var backupPath = $"{PocketVoicesJsonPath}.{timestamp}.bak";
try { File.Copy(PocketVoicesJsonPath, backupPath, true); }
catch (Exception ex) { Log($"Failed to create pocketvoices backup: {ex.Message}", "Warning"); }
}
File.Move(tmpPath, PocketVoicesJsonPath, true);
Log($"Saved {customEntries.Count} custom voice mappings to {PocketVoicesJsonPath}");
}
catch (Exception ex)
{
Log($"Error saving {PocketVoicesJsonPath}: {ex.Message}", "Error");
}
}
private static async Task<bool> EnsurePocketServerStarted()
{
lock (_pocketServerLock)
{
if (_pocketServerStarted && _pocketServerProcess != null && !_pocketServerProcess.HasExited)
return true;
try
{
var executable = ConfigurationManager.AppSettings.Get("PocketTTS_Executable") ?? "uvx";
var uvxPath = ConfigurationManager.AppSettings.Get("PocketTTS_UvxPath") ?? "uvx";
var pocketTtsPath = ConfigurationManager.AppSettings.Get("PocketTTS_PocketTTSPath") ?? "pocket-tts";
var gitUrl = ConfigurationManager.AppSettings.Get("PocketTTS_GitUrl") ?? "git+https://github.com/N6UDP/pocket-tts.git";
var host = ConfigurationManager.AppSettings.Get("PocketTTS_ServerHost") ?? "localhost";
var port = ConfigurationManager.AppSettings.Get("PocketTTS_ServerPort") ?? "8000";
var defaultVoice = ConfigurationManager.AppSettings.Get("PocketTTS_DefaultVoice") ?? "alba";
var hfToken = ConfigurationManager.AppSettings.Get("HuggingFace_Token") ?? "";
var localPathsFlag = _pocketLocalPaths ? " --local-paths" : "";
var device = ConfigurationManager.AppSettings.Get("PocketTTS_Device") ?? "";
var deviceFlag = !string.IsNullOrWhiteSpace(device) ? $" --device {device}" : "";
string fileName;
string arguments;
if (executable.Equals("uvx", StringComparison.OrdinalIgnoreCase))
{
fileName = uvxPath;
arguments = $"--with soundfile --from {gitUrl} pocket-tts serve --host {host} --port {port} --voice {defaultVoice}{localPathsFlag}{deviceFlag}";
}
else if (executable.Equals("pocket-tts", StringComparison.OrdinalIgnoreCase))
{
fileName = pocketTtsPath;
arguments = $"serve --host {host} --port {port} --voice {defaultVoice}{localPathsFlag}{deviceFlag}";
}
else
{
// Custom command — split first token as filename, rest as prefix
var parts = executable.Split(' ', 2);
fileName = parts[0];
var prefix = parts.Length > 1 ? parts[1] + " " : "";
arguments = $"{prefix}serve --host {host} --port {port} --voice {defaultVoice}{localPathsFlag}{deviceFlag}";
}
Log($"Starting PocketTTS server: {fileName} {arguments}");
var startInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
// Pass HuggingFace token as env var if configured
if (!string.IsNullOrEmpty(hfToken))
{
startInfo.EnvironmentVariables["HF_TOKEN"] = hfToken;
Log("HuggingFace token set for PocketTTS server process");
}
_pocketServerProcess = new Process { StartInfo = startInfo };
_pocketServerProcess.OutputDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
Log($"PocketTTS: {e.Data}");
};
_pocketServerProcess.ErrorDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
Log($"PocketTTS STDERR: {e.Data}", "Warning");
};
_pocketServerProcess.Start();
_pocketServerProcess.BeginOutputReadLine();
_pocketServerProcess.BeginErrorReadLine();
_pocketServerStarted = true;
Log($"PocketTTS server started on {host}:{port}");
return true;
}
catch (Exception ex)
{
Log($"Failed to start PocketTTS server: {ex.Message}", "Error");
return false;
}
}
}
private static async Task WaitForPocketServerReady()
{
var host = ConfigurationManager.AppSettings.Get("PocketTTS_ServerHost") ?? "localhost";
var port = ConfigurationManager.AppSettings.Get("PocketTTS_ServerPort") ?? "8000";
var startupTimeout = int.Parse(ConfigurationManager.AppSettings.Get("PocketTTS_StartupTimeout") ?? "120");
var retryInterval = int.Parse(ConfigurationManager.AppSettings.Get("PocketTTS_RetryInterval") ?? "3");
var maxRetries = startupTimeout / retryInterval;
Log($"Waiting for PocketTTS server to be ready (timeout: {startupTimeout}s, retry interval: {retryInterval}s)...");
for (int attempt = 0; attempt < maxRetries; attempt++)
{
try
{
var response = await _httpClient.GetAsync($"http://{host}:{port}/health");
if (response.IsSuccessStatusCode)
{
Log($"PocketTTS server is ready! (took {attempt * retryInterval}s)");
return;
}
else
{
Log($"PocketTTS health check returned {response.StatusCode}, retrying in {retryInterval}s... (attempt {attempt + 1}/{maxRetries})");
}
}
catch (Exception ex)
{
Log($"PocketTTS not ready yet: {ex.Message}, retrying in {retryInterval}s... (attempt {attempt + 1}/{maxRetries})");
}
await Task.Delay(retryInterval * 1000);
}
Log($"PocketTTS server did not become ready within {startupTimeout}s timeout", "Warning");
}
public static void CleanupPocketTTSServer()
{
lock (_pocketServerLock)
{
if (_pocketServerProcess != null && !_pocketServerProcess.HasExited)
{
try
{
Log("Shutting down PocketTTS server (killing process tree)...");
// Kill the entire process tree — uvx spawns a child Python process
// that would otherwise remain running as an orphan
_pocketServerProcess.Kill(entireProcessTree: true);
_pocketServerProcess.WaitForExit(5000);
Log("PocketTTS process tree killed");
}
catch (Exception ex)
{
Log($"Error killing PocketTTS process tree: {ex.Message}", "Warning");
}
finally
{
try { _pocketServerProcess.Dispose(); } catch { }
_pocketServerProcess = null;
_pocketServerStarted = false;
}
}
else
{
// Process already exited or was null — clean up reference
if (_pocketServerProcess != null)
{
try { _pocketServerProcess.Dispose(); } catch { }
_pocketServerProcess = null;
}
_pocketServerStarted = false;
}
// Fallback: kill any process still listening on the PocketTTS port
KillProcessOnPort(ConfigurationManager.AppSettings.Get("PocketTTS_ServerPort") ?? "8000");
}
}
private static void KillProcessOnPort(string port)
{
try
{
// Use netstat to find PID listening on the port
var netstat = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/c netstat -ano | findstr \"LISTENING\" | findstr \":{port} \"",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
netstat.Start();
var output = netstat.StandardOutput.ReadToEnd();
netstat.WaitForExit(3000);
if (string.IsNullOrWhiteSpace(output)) return;
// Parse PIDs from netstat output (last column)
var pids = new HashSet<int>();
foreach (var line in output.Split('\n', StringSplitOptions.RemoveEmptyEntries))
{
var parts = line.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 0 && int.TryParse(parts[^1], out var pid) && pid > 0)
{
pids.Add(pid);
}
}
foreach (var pid in pids)
{
try
{
var proc = Process.GetProcessById(pid);
Log($"Killing orphaned process on port {port}: PID {pid} ({proc.ProcessName})");
proc.Kill(entireProcessTree: true);
proc.WaitForExit(3000);
}
catch (ArgumentException)
{
// Process already exited
}
catch (Exception ex)
{
Log($"Failed to kill PID {pid}: {ex.Message}", "Warning");
}
}
}
catch (Exception ex)
{
Log($"Port cleanup fallback failed: {ex.Message}", "Warning");
}
}
/// <summary>
/// Stream PocketTTS audio directly into a MemoryStream via ffmpeg, without a temp file.
/// Downloads the WAV from the PocketTTS server and pipes it through ffmpeg stdin → stdout.
/// </summary>
private async Task<bool> StreamPocketTTSAudio(string text, string voice, MemoryStream destination)
{
var host = ConfigurationManager.AppSettings.Get("PocketTTS_ServerHost") ?? "localhost";
var port = ConfigurationManager.AppSettings.Get("PocketTTS_ServerPort") ?? "8000";
var requestTimeout = int.Parse(ConfigurationManager.AppSettings.Get("PocketTTS_RequestTimeout") ?? "60");
// Resolve voice: strip Pocket_ prefix
string resolvedVoice;
if (pocketVoiceModels.TryGetValue(voice, out var mapped))
{
resolvedVoice = mapped;
}
else
{
resolvedVoice = voice.StartsWith("Pocket_", StringComparison.OrdinalIgnoreCase)
? voice.Substring(7)
: voice;
}
try
{
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(requestTimeout) };
using var formContent = new MultipartFormDataContent();
formContent.Add(new StringContent(text), "text");
if (File.Exists(resolvedVoice))
{
if (_pocketLocalPaths)
{
var absolutePath = Path.GetFullPath(resolvedVoice);
formContent.Add(new StringContent(absolutePath), "voice_url");
}
else
{
var fileBytes = await File.ReadAllBytesAsync(resolvedVoice);
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
formContent.Add(fileContent, "voice_wav", Path.GetFileName(resolvedVoice));
}
}
else if (resolvedVoice.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
|| resolvedVoice.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
|| resolvedVoice.StartsWith("hf://", StringComparison.OrdinalIgnoreCase))
{
formContent.Add(new StringContent(resolvedVoice), "voice_url");
}
else
{
formContent.Add(new StringContent(resolvedVoice), "voice_url");
}
Log($"PocketTTS request: text='{text}', voice='{resolvedVoice}'");
var response = await client.PostAsync($"http://{host}:{port}/tts", formContent);
if (!response.IsSuccessStatusCode)
{
var errorBody = await response.Content.ReadAsStringAsync();
Log($"PocketTTS API failed: {response.StatusCode} — {errorBody}", "Error");
return false;
}
// Pipe the WAV response directly into ffmpeg stdin → PCM stdout, no temp file
using var wavStream = await response.Content.ReadAsStreamAsync();
using var ffmpeg = Process.Start(new ProcessStartInfo
{
FileName = ConfigurationManager.AppSettings.Get("ffmpeg"),
Arguments = "-hide_banner -loglevel panic -i pipe:0 -ac 2 -f s16le -ar 48000 pipe:1",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
});
// Write WAV to ffmpeg stdin and read PCM from stdout concurrently
var writeTask = Task.Run(async () =>
{
try
{
await wavStream.CopyToAsync(ffmpeg.StandardInput.BaseStream);
}
finally
{
ffmpeg.StandardInput.Close();
}
});
await ffmpeg.StandardOutput.BaseStream.CopyToAsync(destination);
await writeTask;
Log($"PocketTTS streamed audio: {destination.Length} bytes (no temp file)");
return true;
}
catch (Exception ex)
{
Log($"PocketTTS streaming error: {ex.Message}", "Error");
return false;
}
}
// ==================== Voice Upload/Rename/Delete Commands ====================
private static bool IsUserAllowedToUpload(ulong userId)
{
var allowlist = ConfigurationManager.AppSettings.Get("PocketTTS_VoiceUploadAllowlist") ?? "";
if (string.IsNullOrWhiteSpace(allowlist)) return false;
if (allowlist.Trim() == "*") return true;
return allowlist.Split(',').Select(s => s.Trim()).Any(id => id == userId.ToString());
}
private static string BuildPocketTTSCommand(string subCommand, string extraArgs)
{
var executable = ConfigurationManager.AppSettings.Get("PocketTTS_Executable") ?? "uvx";
var uvxPath = ConfigurationManager.AppSettings.Get("PocketTTS_UvxPath") ?? "uvx";
var pocketTtsPath = ConfigurationManager.AppSettings.Get("PocketTTS_PocketTTSPath") ?? "pocket-tts";
var gitUrl = ConfigurationManager.AppSettings.Get("PocketTTS_GitUrl") ?? "git+https://github.com/N6UDP/pocket-tts.git";
if (executable.Equals("uvx", StringComparison.OrdinalIgnoreCase))
{
return $"{uvxPath} --with soundfile --from {gitUrl} pocket-tts {subCommand} {extraArgs}";
}
else if (executable.Equals("pocket-tts", StringComparison.OrdinalIgnoreCase))
{
return $"{pocketTtsPath} {subCommand} {extraArgs}";
}
else
{
// Custom command — split first token as filename, rest as prefix
var parts = executable.Split(' ', 2);
var prefix = parts.Length > 1 ? parts[1] + " " : "";
return $"{parts[0]} {prefix}{subCommand} {extraArgs}";
}
}
/// <summary>
/// Build CLI flags for export-voice from user-specified parameters.
/// Only non-null/non-default values are appended.
/// </summary>
private static string BuildExportVoiceArgs(
bool truncate = false,
int? lsdDecodeSteps = null,
float? temperature = null,
float? noiseClamp = null,
float? eosThreshold = null,
int? framesAfterEos = null)
{
var parts = new List<string>();
if (truncate) parts.Add("--truncate");
if (lsdDecodeSteps.HasValue) parts.Add($"--lsd-decode-steps {lsdDecodeSteps.Value}");
if (temperature.HasValue) parts.Add($"--temperature {temperature.Value}");
if (noiseClamp.HasValue) parts.Add($"--noise-clamp {noiseClamp.Value}");
if (eosThreshold.HasValue) parts.Add($"--eos-threshold {eosThreshold.Value}");
if (framesAfterEos.HasValue) parts.Add($"--frames-after-eos {framesAfterEos.Value}");
return parts.Count > 0 ? " " + string.Join(" ", parts) : "";
}
public async Task UploadVoice(string name, ulong userId, TextChannel textChannel, string attachmentUrl, string fileName,
bool truncate = false,
int? lsdDecodeSteps = null, float? temperature = null, float? noiseClamp = null,
float? eosThreshold = null, int? framesAfterEos = null)
{
if (!_enablePocketTTS)
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "PocketTTS engine is disabled." });
return;
}
if (!IsUserAllowedToUpload(userId))
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "You don't have permission to upload custom voices." });
return;
}
var voiceDir = ConfigurationManager.AppSettings.Get("PocketTTS_VoiceDirectory") ?? "";
if (string.IsNullOrEmpty(voiceDir))
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Custom voice storage is not configured. Set PocketTTS_VoiceDirectory in App.config." });
return;
}
// Check name doesn't conflict with predefined voices
if (PocketPredefinedVoices.Contains(name, StringComparer.OrdinalIgnoreCase))
{
await textChannel.SendMessageAsync(new MessageProperties { Content = $"Cannot use that name — it conflicts with a built-in voice: {name}" });
return;
}
// Validate file extension
var ext = Path.GetExtension(fileName).ToLowerInvariant();
if (ext != ".wav" && ext != ".mp3" && ext != ".safetensors")
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Unsupported file type. Please upload a .wav, .mp3, or .safetensors file." });
return;
}
// Validate file size
var maxSizeMB = int.Parse(ConfigurationManager.AppSettings.Get("PocketTTS_MaxUploadSizeMB") ?? "10");
try
{
await textChannel.SendMessageAsync(new MessageProperties { Content = $"Processing voice upload '{name}'..." });
// Download the attachment
using var client = new HttpClient();
var data = await client.GetByteArrayAsync(attachmentUrl);
if (data.Length > maxSizeMB * 1024 * 1024)
{
await textChannel.SendMessageAsync(new MessageProperties { Content = $"File exceeds maximum size of {maxSizeMB}MB." });
return;
}
var outputPath = Path.Combine(voiceDir, $"{name}.safetensors");
if (ext == ".safetensors")
{
// Copy directly
await File.WriteAllBytesAsync(outputPath, data);
Log($"Voice upload: copied .safetensors directly to {outputPath}");
}
else
{
// Save temp file and run export-voice
var tempInput = Path.GetTempFileName() + ext;
await File.WriteAllBytesAsync(tempInput, data);
try
{
var exportVoiceFlags = BuildExportVoiceArgs(truncate,
lsdDecodeSteps, temperature, noiseClamp, eosThreshold, framesAfterEos);
var device = ConfigurationManager.AppSettings.Get("PocketTTS_Device") ?? "";
if (!string.IsNullOrWhiteSpace(device)) exportVoiceFlags += $" --device {device}";
var fullCmd = BuildPocketTTSCommand("export-voice", $"\"{tempInput}\" \"{outputPath}\"{exportVoiceFlags}");
// Parse the command
var cmdParts = fullCmd.Split(' ', 2);
var startInfo = new ProcessStartInfo
{
FileName = cmdParts[0],
Arguments = cmdParts.Length > 1 ? cmdParts[1] : "",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
var hfToken = ConfigurationManager.AppSettings.Get("HuggingFace_Token") ?? "";
if (!string.IsNullOrEmpty(hfToken))
{
startInfo.EnvironmentVariables["HF_TOKEN"] = hfToken;
}
Log($"Running export-voice: {fullCmd}");
var process = new Process { StartInfo = startInfo };
process.Start();
var stdout = await process.StandardOutput.ReadToEndAsync();
var stderr = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
if (!string.IsNullOrEmpty(stdout)) Log($"export-voice stdout: {stdout}");
if (!string.IsNullOrEmpty(stderr)) Log($"export-voice stderr: {stderr}", "Warning");
if (process.ExitCode != 0 || !File.Exists(outputPath))
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Failed to process voice sample. The audio file may be corrupted or too short." });
if (!string.IsNullOrEmpty(hfToken))
{
// Token was set, maybe other issue
}
else
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Note: HuggingFace token may be required for voice processing. Set HuggingFace_Token in App.config and accept terms at <https://huggingface.co/kyutai/pocket-tts>" });
}
return;
}
}
finally
{
if (File.Exists(tempInput)) File.Delete(tempInput);
}
}
// Register the new voice and persist to JSON
var voiceKey = $"Pocket_{name}";
pocketVoiceModels[voiceKey] = outputPath;
SavePocketVoicesJson();
Log($"Voice uploaded and registered: {voiceKey} → {outputPath}");
await textChannel.SendMessageAsync(new MessageProperties { Content = $"✅ Voice uploaded! Use: `!tts changevoice {voiceKey}`" });
}
catch (Exception ex)
{
Log($"Voice upload error: {ex.Message}", "Error");
await textChannel.SendMessageAsync(new MessageProperties { Content = $"Error uploading voice: {ex.Message}" });
}
}
public async Task RenameVoice(string oldName, string newName, ulong userId, TextChannel textChannel)