-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path98_Text2Speech.pm
1870 lines (1620 loc) · 75.5 KB
/
98_Text2Speech.pm
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
##############################################
# $Id: 98_Text2Speech.pm 25785 2022-07-10 Beta-User - Mimic 3 version $
#
# 98_Text2Speech.pm
#
# written by Tobias Faust 2013-10-23
# e-mail: tobias dot faust at gmx dot net
#
##############################################
##############################################
# EDITOR=nano
# visudo
# ALL ALL = NOPASSWD: /usr/bin/mplayer
##############################################
package main;
use strict;
use warnings;
use Blocking;
use HttpUtils;
# use Data::Dumper;
use lib ('./FHEM/lib', './lib');
sub Text2Speech_OpenDev($);
sub Text2Speech_CloseDev($);
# SetParamName -> Anzahl Paramter
my %sets = (
"tts" => "1",
"volume" => "1"
);
# path to mplayer
my $mplayer = 'sudo /usr/bin/mplayer';
my $mplayerOpts = '-nolirc -noconsolecontrols';
my $mplayerNoDebug = '-really-quiet';
my $mplayerAudioOpts = '-ao alsa:device=';
my %ttsHost = ("Google" => "translate.google.com",
"VoiceRSS" => "api.voicerss.org"
);
my %ttsLang = ("Google" => "tl=",
"VoiceRSS" => "hl="
);
my %ttsQuery = ("Google" => "q=",
"VoiceRSS" => "src="
);
my %ttsPath = ("Google" => "/translate_tts?",
"VoiceRSS" => "/?"
);
my %ttsAddon = ("Google" => "client=tw-ob&ie=UTF-8",
"VoiceRSS" => ""
);
my %ttsAPIKey = ("Google" => "", # kein APIKey nötig
"VoiceRSS" => "key=",
maryTTS => ''
);
my %ttsUser = ("Google" => "", # kein Username nötig
"VoiceRSS" => "" # kein Username nötig
);
my %ttsSpeed = ("Google" => "",
"VoiceRSS" => "r="
);
my %ttsQuality = ("Google" => "",
"VoiceRSS" => "f="
);
my %ttsMaxChar = ("Google" => 200,
"VoiceRSS" => 300,
"SVOX-pico" => 1000,
"Amazon-Polly" => 3000,
maryTTS => 3000
);
my %language = ("Google" => { "Deutsch" => "de",
"English-US" => "en-us",
"Schwedisch" => "sv",
"France" => "fr",
"Spain" => "es",
"Italian" => "it",
"Chinese" => "cn",
"Dutch" => "nl"
},
"VoiceRSS" => { "Deutsch" => "de-de",
"English-US" => "en-us",
"Schwedisch" => "sv-se",
"France" => "fr-fr",
"Spain" => "es-es",
"Italian" => "it-it",
"Chinese" => "zh-cn",
"Dutch" => "nl-nl"
},
"SVOX-pico" => { "Deutsch" => "de-DE",
"English-US" => "en-US",
"France" => "fr-FR",
"Spain" => "es-ES",
"Italian" => "it-IT"
},
"Amazon-Polly"=> {"Deutsch" => "Marlene",
"English-US" => "Joanna",
"Schwedisch" => "Astrid",
"France" => "Celine",
"Spain" => "Conchita",
"Italian" => "Carla",
"Chinese" => "Zhiyu",
"Dutch" => "Lotte"
}
);
##########################
sub Text2Speech_Initialize($)
{
my ($hash) = @_;
$hash->{WriteFn} = "Text2Speech_Write";
$hash->{ReadyFn} = "Text2Speech_Ready";
$hash->{DefFn} = "Text2Speech_Define";
$hash->{SetFn} = "Text2Speech_Set";
$hash->{UndefFn} = "Text2Speech_Undefine";
$hash->{AttrFn} = "Text2Speech_Attr";
$hash->{AttrList} = "disable:0,1".
" TTS_Delimiter".
" TTS_Ressource:ESpeak,SVOX-pico,Amazon-Polly,maryTTS,". join(",", sort keys %ttsHost).
" TTS_APIKey".
" TTS_User".
" TTS_Quality:".
"48khz_16bit_stereo,".
"48khz_16bit_mono,".
"48khz_8bit_stereo,".
"48khz_8bit_mono".
"44khz_16bit_stereo,".
"44khz_16bit_mono,".
"44khz_8bit_stereo,".
"44khz_8bit_mono".
"32khz_16bit_stereo,".
"32khz_16bit_mono,".
"32khz_8bit_stereo,".
"32khz_8bit_mono".
"24khz_16bit_stereo,".
"24khz_16bit_mono,".
"24khz_8bit_stereo,".
"24khz_8bit_mono".
"22khz_16bit_stereo,".
"22khz_16bit_mono,".
"22khz_8bit_stereo,".
"22khz_8bit_mono".
"16khz_16bit_stereo,".
"16khz_16bit_mono,".
"16khz_8bit_stereo,".
"16khz_8bit_mono".
"8khz_16bit_stereo,".
"8khz_16bit_mono,".
"8khz_8bit_stereo,".
"8khz_8bit_mono".
" TTS_Speed:-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10".
" TTS_TimeOut".
" TTS_CacheFileDir".
" TTS_UseMP3Wrap:0,1".
" TTS_MplayerCall".
" TTS_SentenceAppendix".
" TTS_FileMapping".
" TTS_FileTemplateDir".
" TTS_VolumeAdjust".
" TTS_noStatisticsLog:1,0".
" TTS_Language:".join(",", sort keys %{$language{"Google"}}).
" TTS_Language_Custom".
" TTS_SpeakAsFastAsPossible:1,0".
" TTS_OutputFile".
" TTS_AWS_HomeDir".
" ".$readingFnAttributes;
}
##########################
# Define <tts> Text2Speech <alsa-device>
# Define <tts> Text2Speech host[:port][:SSL] [portpassword]
##########################
sub Text2Speech_Define($$)
{
my ($hash, $def) = @_;
my @a = split("[ \t]+", $def);
#$a[0]: Name
#$a[1]: Type/Alias -> Text2Speech
#$a[2]: definition
#$a[3]: optional: portpasswd
if(int(@a) < 3) {
my $msg = "wrong syntax: define <name> Text2Speech <alsa-device>\n".
"see at /etc/asound.conf\n".
"or remote syntax: define <name> Text2Speech host[:port][:SSL] [portpassword]";
Log3 $hash, 2, $msg;
return $msg;
}
my $dev = $a[2];
if($dev =~ m/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*/ ) {
# Ein RemoteDevice ist angegeben
# zb: 192.168.10.24:7272:SSL mypasswd
if($dev =~ m/^(.*):SSL$/) {
$dev = $1;
$hash->{SSL} = 1;
}
if($dev !~ m/^.+:[0-9]+$/) { # host:port
$dev = "$dev:7072";
}
$hash->{Host} = $dev;
$hash->{portpassword} = $a[3] if(@a == 4);
$hash->{MODE} = "REMOTE";
} elsif (lc($dev) eq "none") {
# Ein DummyDevice, Serverdevice. Nur Generierung der mp3 TTS Dateien
$hash->{MODE} = "SERVER";
undef $hash->{ALSADEVICE};
} else {
# Ein Alsadevice ist angegeben
# pruefen, ob Alsa-Device in /etc/asound.conf definiert ist
$hash->{MODE} = "DIRECT";
$hash->{ALSADEVICE} = $a[2];
}
BlockingKill($hash->{helper}{RUNNING_PID}) if(defined($hash->{helper}{RUNNING_PID}));
delete($hash->{helper}{RUNNING_PID});
$hash->{STATE} = "Initialized";
my $ret = Text2Speech_loadmodules($hash, "");
if ($ret) {
Log3 $hash->{NAME}, 3, $ret;
}
return undef;
}
##########################
# Überprüfung und Einladen der notwendigen Module
##########################
sub Text2Speech_loadmodules($$) {
my ($hash, $TTS_Ressource) = @_;
eval {
require IO::File;
IO::File->import;
1;
} or return "IO::File Module not installed. Please install.";
eval {
require Digest::MD5;
Digest::MD5->import;
1;
} or return "Digest::MD5 Module not installed. Please install.";
eval {
require URI::Escape;
URI::Escape->import;
1;
} or return "URI::Escape Module not installed. Please install.";
eval {
require Text::Iconv;
Text::Iconv->import;
1;
} or return "Text::Iconv Module not installed. Please install.";
eval {
require Encode::Guess;
Encode::Guess->import;
1;
} or return "Encode::Guess Module not installed. Please install.";
eval {
require MP3::Info;
MP3::Info->import;
1;
} or return "MP3::Info Module not installed. Please install.";
if ($TTS_Ressource eq "Amazon-Polly") {
# Module werden nur benötigt mit der Polly Engine
eval {
require Paws::Polly;
Paws::Polly->import;
1;
} or return "Paws Module not installed. Please install via 'sudo cpan Paws'.";
eval {
require File::HomeDir;
File::HomeDir->import;
1;
} or return "File::HomeDir Module not installed. Please install";
}
return undef;
}
#####################################
sub Text2Speech_Undefine($$)
{
my ($hash, $arg) = @_;
RemoveInternalTimer($hash);
BlockingKill($hash->{helper}{RUNNING_PID}) if(defined($hash->{helper}{RUNNING_PID}));
Text2Speech_CloseDev($hash);
return undef;
}
sub Text2Speech_Attr(@) {
my @a = @_;
my $do = 0;
my $hash = $defs{$a[1]};
my $value = $a[3];
my $TTS_FileTemplateDir = AttrVal($hash->{NAME}, "TTS_FileTemplateDir", "templates");
my $TTS_CacheFileDir = AttrVal($hash->{NAME}, "TTS_CacheFileDir", "cache");
my $TTS_FileMapping = AttrVal($hash->{NAME}, "TTS_FileMapping", ""); # zb, silence:silence.mp3 ring:myringtone.mp3;
my $TTS_AWS_HomeDir = AttrVal($hash->{NAME}, "TTS_AWS_HomeDir", "/home/fhem");
if($a[2] eq "TTS_Delimiter" && $a[0] ne "del") {
return "wrong Delimiter syntax: [+-]a[lfn]. Please see CommandRef for Notation. \n".
" Example 1: +an~\n".
" Example 2: +al." if($value !~ m/^([+-]a[lfn]){0,1}(.){1}$/i);
return "This Attribute is only available in direct or server mode" if($hash->{MODE} !~ m/(DIRECT|SERVER)/ );
} elsif ($a[0] eq "set" && $a[2] eq "TTS_Ressource" && $value eq "Amazon-Polly") {
Log3 $hash->{NAME}, 4, $hash->{NAME}. ": Wechsele auf Amazon Polly, Lade Librarys nach.";
my $ret = Text2Speech_loadmodules($hash, $a[2]);
if ($ret) {return $ret;} # breche ab wenn Module fehlen
if (! -e $TTS_AWS_HomeDir."/.aws/credentials"){
return "No AWS credentials in FHEM Homedir found, please check ".$TTS_AWS_HomeDir."/.aws/credentials \n please refer https://metacpan.org/pod/Paws#AUTHENTICATION \n\n Please check Attribute 'TTS_AWS_HomeDir' too";
}
} elsif ($a[0] eq "set" && $a[2] eq "TTS_Ressource") {
return "This Attribute is only available in direct or server mode" if($hash->{MODE} !~ m/(DIRECT|SERVER)/ );
} elsif ($a[0] eq "set" && $a[2] eq "TTS_CacheFileDir") {
return "This Attribute is only available in direct or server mode" if($hash->{MODE} !~ m/(DIRECT|SERVER)/ );
} elsif ($a[0] eq "set" && $a[2] eq "TTS_SpeakAsFastAsPossible") {
return "This Attribute is only available in direct or server mode" if($hash->{MODE} !~ m/(DIRECT|SERVER)/ );
} elsif ($a[0] eq "set" && $a[2] eq "TTS_UseMP3Wrap") {
return "This Attribute is only available in direct or server mode" if($hash->{MODE} !~ m/(DIRECT|SERVER)/ );
return "Attribute TTS_UseMP3Wrap is required by Attribute TTS_SentenceAppendix! Please delete it first."
if(($a[0] eq "del") && (AttrVal($hash->{NAME}, "TTS_SentenceAppendix", undef)));
} elsif ($a[0] eq "set" && $a[2] eq "TTS_SentenceAppendix") {
return "This Attribute is only available in direct or server mode" if($hash->{MODE} !~ m/(DIRECT|SERVER)/ );
return "Attribute TTS_UseMP3Wrap is required!" unless(AttrVal($hash->{NAME}, "TTS_UseMP3Wrap", undef));
my $file = $TTS_CacheFileDir ."/". $value;
return "File <".$file."> does not exists in CacheFileDir" if(! -e $file);
} elsif ($a[0] eq "set" && $a[2] eq "TTS_FileTemplateDir") {
# Verzeichnis beginnt mit /, dann absoluter Pfad, sonst Unterpfad von $TTS_CacheFileDir
my $newDir;
if($value =~ m/^\/.*/) { $newDir = $value; } else { $newDir = $TTS_CacheFileDir ."/". $value;}
unless(-e ($newDir) or mkdir ($newDir)) {
#Verzeichnis anlegen gescheitert
return "Could not create directory: <$value>";
}
} elsif ($a[0] eq "set" && $a[2] eq "TTS_TimeOut") {
return "Only Numbers allowed" if ($value !~ m/[0-9]+/);
} elsif ($a[0] eq "set" && $a[2] eq "TTS_AWS_HomeDir") {
return "Your HomeDir cannot be found." if (! -e $value)
} elsif ($a[0] eq "set" && $a[2] eq "TTS_FileMapping") {
#Bsp: silence:silence.mp3 pling:mypling,mp3
#ueberpruefen, ob mp3 Template existiert
my @FileTpl = split(" ", $TTS_FileMapping);
my $newDir;
for(my $j=0; $j<(@FileTpl); $j++) {
my @FileTplPc = split(/:/, $FileTpl[$j]);
if($TTS_FileTemplateDir =~ m/^\/.*/) { $newDir = $TTS_FileTemplateDir; } else { $newDir = $TTS_CacheFileDir ."/". $TTS_FileTemplateDir;}
return "file does not exist: <".$newDir ."/". $FileTplPc[1] .">"
unless (-e $newDir ."/". $FileTplPc[1]);
}
}
if($a[0] eq "set" && $a[2] eq "disable") {
$do = (!defined($a[3]) || $a[3]) ? 1 : 2;
}
$do = 2 if($a[0] eq "del" && (!$a[2] || $a[2] eq "disable"));
return if(!$do);
$hash->{STATE} = ($do == 1 ? "disabled" : "Initialized");
return undef;
}
#####################################
sub Text2Speech_Ready($)
{
my ($hash) = @_;
return Text2speech_OpenDev($hash, 1);
}
########################
sub Text2Speech_OpenDev($) {
my ($hash) = @_;
my $dev = $hash->{Host};
my $name = $hash->{NAME};
Log3 $name, 4, "Text2Speech opening $name at $dev";
my $conn;
if($hash->{SSL}) {
eval "use IO::Socket::SSL";
Log3 $name, 1, $@ if($@);
$conn = IO::Socket::SSL->new(PeerAddr => "$dev", MultiHomed => 1) if(!$@);
} else {
$conn = IO::Socket::INET->new(PeerAddr => $dev, MultiHomed => 1);
}
if(!$conn) {
Log3($name, 3, $hash->{NAME}.": Can't connect to $dev: $!");
$hash->{STATE} = "disconnected";
return "";
} else {
$hash->{STATE} = "Initialized";
}
$hash->{TCPDev} = $conn;
$hash->{FD} = $conn->fileno();
Log3 $name, 4, "Text2Speech device opened ($name)";
syswrite($hash->{TCPDev}, $hash->{portpassword} . "\n")
if($hash->{portpassword});
return undef;
}
########################
sub Text2Speech_CloseDev($) {
my ($hash) = @_;
my $name = $hash->{NAME};
my $dev = $hash->{Host};
return if(!$dev);
if($hash->{TCPDev}) {
$hash->{TCPDev}->close();
Log3 $hash, 4, "Text2speech Device closed ($name)";
}
delete($hash->{TCPDev});
delete($hash->{FD});
}
########################
sub Text2Speech_Write($$) {
my ($hash,$msg) = @_;
my $name = $hash->{NAME};
my $dev = $hash->{Host};
#my $call = "set tts tts Das ist ein Test.";
my $call = "set $name $msg";
#Prüfen ob PRESENCE vorhanden und present
my $isPresent = 0;
my $hasPRESENCE = 0;
my $devname="";
if ($hash->{MODE} eq "REMOTE") {
foreach $devname (devspec2array("TYPE=PRESENCE")) {
if (defined $defs{$devname}->{ADDRESS} && $dev) {
if ($dev =~ $defs{$devname}->{ADDRESS}) {
$hasPRESENCE = 1;
$isPresent = 1 if (ReadingsVal($devname,"presence","unknown") eq "present");
last;
}
}
}
}
if ($hasPRESENCE) {
Log3 $hash, 4, $name.": found PRESENCE Device $devname for host: $dev, it\'s state is: ".($isPresent ? "present" : "absent");
Text2Speech_OpenDev($hash) if(!$hash->{TCPDev} && $isPresent);
#lets try again
Text2Speech_OpenDev($hash) if(!$hash->{TCPDev} && $isPresent);
} else {
Log3 $hash, 4, $name.": no proper PRESENCE Device for host: $dev";
Text2Speech_OpenDev($hash) if(!$hash->{TCPDev});
#lets try again
Text2Speech_OpenDev($hash) if(!$hash->{TCPDev});
}
if($hash->{TCPDev}) {
Log3 $hash, 4, $name.": Write remote message to $dev: $call";
Log3 $hash, 3, $name.": Could not write remote message ($call) at " .$hash->{Host} if(!defined(syswrite($hash->{TCPDev}, "$call\n")));
Text2Speech_CloseDev($hash);
}
}
###########################################################################
sub Text2Speech_Set($@)
{
my ($hash, @a) = @_;
my $me = $hash->{NAME};
my $TTS_APIKey = AttrVal($hash->{NAME}, "TTS_APIKey", undef);
my $TTS_User = AttrVal($hash->{NAME}, "TTS_User", undef);
my $TTS_Ressource = AttrVal($hash->{NAME}, "TTS_Ressource", "Google");
my $TTS_TimeOut = AttrVal($hash->{NAME}, "TTS_TimeOut", 60);
return "no set argument specified" if(int(@a) < 2);
return "No APIKey specified" if (!defined($TTS_APIKey) && ($ttsAPIKey{$TTS_Ressource} || length($ttsAPIKey{$TTS_Ressource})>0));
return "No Username for TTS Access specified" if ( $TTS_Ressource ne 'maryTTS' && !defined($TTS_User) && ($ttsUser{$TTS_Ressource} || length($ttsUser{$TTS_Ressource})>0));
my $ret = Text2Speech_loadmodules($hash, $TTS_Ressource);
if ($ret) {
# breche ab wenn Module fehlen
Log3 $me, 3, $ret;
return $ret;
}
my $cmd = shift(@a); # Dummy
$cmd = shift(@a); # DevName
if(!defined($sets{$cmd})) {
my $r = "Unknown argument $cmd, choose one of ".join(" ",sort keys %sets);
return $r;
}
if($cmd ne "tts") {
return "$cmd needs $sets{$cmd} parameter(s)" if(@a-$sets{$cmd} != 0);
} else {
return "$cmd needs text parameter" if(@a-$sets{$cmd} < 0);
}
# Abbruch falls Disabled
return "no set cmd on a disabled device !" if(IsDisabled($me));
if($cmd eq "tts") {
if($hash->{MODE} eq "DIRECT" || $hash->{MODE} eq "SERVER") {
$hash->{VOLUME} = ReadingsNum($me, "volume", 100);
readingsSingleUpdate($hash, "playing", "1", 1);
Text2Speech_PrepareSpeech($hash, join(" ", @a));
$hash->{helper}{RUNNING_PID} = BlockingCall("Text2Speech_DoIt", $hash, "Text2Speech_Done", $TTS_TimeOut, "Text2Speech_AbortFn", $hash) unless(exists($hash->{helper}{RUNNING_PID}));
} elsif ($hash->{MODE} eq "REMOTE") {
Text2Speech_Write($hash, "tts " . join(" ", @a));
} else {return undef;}
} elsif($cmd eq "volume") {
my $vol = join(" ", @a);
return "volume level expects 0..100 percent" if($vol !~ m/^([0-9]{1,3})$/ or $vol > 100);
if($hash->{MODE} eq "DIRECT") {
$hash->{VOLUME} = $vol if($vol <= 100);
delete($hash->{VOLUME}) if($vol > 100);
} elsif ($hash->{MODE} eq "REMOTE") {
Text2Speech_Write($hash, "volume $vol");
} else {return undef;}
readingsSingleUpdate($hash, "volume", (($vol>100)?0:$vol), 1);
}
return undef;
}
#####################################
# Bereitet den gesamten String vor.
# Bei Nutzung Google wird dieser in ein Array
# zerlegt mit jeweils einer maximalen
# Stringlänge von 100Chars
#
# param1: $hash
# param2: string to speech
#
#####################################
###################################
# Angabe des Delimiters: zb.: +af~
# + -> erzwinge das Trennen, auch wenn Textbaustein < 100Zeichen
# - -> Trenne nur wenn Textbaustein > 100Zeichen
# af -> add first -> füge den Delimiter am Satzanfang wieder hinzu
# al -> add last -> füge den Delimiter am Satzende wieder hinzu
# an -> add nothing -> Delimiter nicht wieder hinzufügen
# ~ -> der Delimiter
###################################
sub Text2Speech_PrepareSpeech($$) {
my ($hash, $t) = @_;
my $me = $hash->{NAME};
my $TTS_Ressource = AttrVal($hash->{NAME}, "TTS_Ressource", "Google");
my $TTS_Delimiter = AttrVal($hash->{NAME}, "TTS_Delimiter", undef);
my $TTS_FileTpl = AttrVal($hash->{NAME}, "TTS_FileMapping", ""); # zb, silence:silence.mp3 ring:myringtone.mp3; im Text: mein Klingelton :ring: ist laut.
my $TTS_FileTemplateDir = AttrVal($hash->{NAME}, "TTS_FileTemplateDir", "templates");
my $TTS_ForceSplit = 0;
my $TTS_AddDelimiter;
# Cleanup string
$hash->{helper}{TTS_PlayerOptions} = "";
while ($t =~ s/^ //isg) {};
$t =~ s/^'(.*)'$/$1/;
$t =~ s/^"(.*)"$/$1/;
# Check text for command string
if ($t =~ /^\[(.*?)\](.*?)$/) {
($hash->{helper}{TTS_PlayerOptions}, $t) = ($1, $2);
while ($t =~ s/^ //isg) {};
}
if($TTS_Delimiter && $TTS_Delimiter =~ m/^[+-]a[lfn]/i) {
$TTS_ForceSplit = 1 if(substr($TTS_Delimiter,0,1) eq "+");
$TTS_ForceSplit = 0 if(substr($TTS_Delimiter,0,1) eq "-");
$TTS_AddDelimiter = substr($TTS_Delimiter,1,2); # af, al oder an
$TTS_Delimiter = substr($TTS_Delimiter,3);
} elsif (!$TTS_Delimiter) { # Default wenn Attr nicht gesetzt
$TTS_Delimiter = "(?<=[\\.!?])\\s*";
$TTS_ForceSplit = 0;
$TTS_AddDelimiter = "";
}
#-- we may have problems with umlaut characters
# ersetze Sonderzeichen die Google nicht auflösen kann
my $converter;
# wandle per standard alles nach UTF8
# check only ascii, utf8 and UTF-(16|32) with BOM, if not enough use function set_suspects
# Encode::Guess->set_suspects(qw/euc-jp shiftjis 7bit-jis/); # for japanese codepages
my $enc = guess_encoding($t);
if ($enc->name ne "utf8") {
Log3 $hash, 4, "$me: ermittelte CodePage: " .$enc->name. " , konvertiere nach UTF-8";
$converter = Text::Iconv->new($enc->name, "utf-8");
$t = $converter->convert($t);
}
#if($TTS_Ressource eq "Google") {
# Google benötigt UTF-8
# $t =~ s/ä/ae/g;
# $t =~ s/ö/oe/g;
# $t =~ s/ü/ue/g;
# $t =~ s/Ä/Ae/g;
# $t =~ s/Ö/Oe/g;
# $t =~ s/Ü/Ue/g;
# $t =~ s/ß/ss/g;
#}
if ($TTS_Ressource eq "Amazon-Polly") {
# Amazon benötigt ISO-8859-1 bei Nutzung Region eu-central-1
$converter = Text::Iconv->new("utf-8", "iso-8859-1");
$t = $converter->convert($t);
}
my @text;
push(@text, $t);
# hole alle Filetemplates
my @FileTpl = split(" ", $TTS_FileTpl);
my @FileTplPc;
# bei Angabe direkter MP3-Files wird hier ein temporäres Template vergeben
for(my $i=0; $i<(@text); $i++) {
@FileTplPc = ($text[$i] =~ /:([\w-]+?\.(?:mp3|ogg|wav)):/g);
for(my $j=0; $j<(@FileTplPc); $j++) {
my $tpl = "FileTpl_#".$i."_".$j; #eindeutige Templatedefinition schaffen
Log3 $hash, 4, "$me: Angabe einer direkten MP3-Datei gefunden: $FileTplPc[$j] => $tpl";
push(@FileTpl, $tpl.":".$FileTplPc[$j]); #zb: FileTpl_123645875_#0:/ring.mp3
$text[$i] =~ s/$FileTplPc[$j]/$tpl/g; # Ersetze die DateiDefinition gegen ein Template
}
}
#iteriere durch die Sprachbausteine und splitte den Text bei den Filetemplates auf
for(my $i=0; $i<(@text); $i++) {
my $cutter = '#!#'; #eindeutigen Cutter als Delimiter bei den Filetemplates vergeben
@FileTplPc = ($text[$i] =~ /:([^:]+):/g);
for(my $j=0; $j<(@FileTplPc); $j++) {
$text[$i] =~ s/:$FileTplPc[$j]:/$cutter$FileTplPc[$j]$cutter/g;
}
@text = Text2Speech_SplitString(\@text, 0, $cutter, 1, "");
}
Log3 $hash, 4, "$me: MaxChar = $ttsMaxChar{$TTS_Ressource}, Delimiter = $TTS_Delimiter, ForceSplit = $TTS_ForceSplit, AddDelimiter = $TTS_AddDelimiter";
@text = Text2Speech_SplitString(\@text, $ttsMaxChar{$TTS_Ressource}, $TTS_Delimiter, $TTS_ForceSplit, $TTS_AddDelimiter);
@text = Text2Speech_SplitString(\@text, $ttsMaxChar{$TTS_Ressource}, "(?<=[.!?])\\s*", 0, "");
@text = Text2Speech_SplitString(\@text, $ttsMaxChar{$TTS_Ressource}, ",", 0, "al");
@text = Text2Speech_SplitString(\@text, $ttsMaxChar{$TTS_Ressource}, ";", 0, "al");
@text = Text2Speech_SplitString(\@text, $ttsMaxChar{$TTS_Ressource}, "und", 0, "af");
@text = Text2Speech_SplitString(\@text, $ttsMaxChar{$TTS_Ressource}, ":", 0, "al");
@text = Text2Speech_SplitString(\@text, $ttsMaxChar{$TTS_Ressource}, "\\bund\\b", 0, "af");
@text = Text2Speech_SplitString(\@text, $ttsMaxChar{$TTS_Ressource}, " ", 0, "");
Log3 $hash, 4, "$me: Auflistung der Textbausteine nach Aufbereitung:";
for(my $i=0; $i<(@text); $i++) {
# entferne führende und abschließende Leerzeichen aus jedem Textbaustein
$text[$i] =~ s/^\s+|\s+$//g;
for(my $j=0; $j<(@FileTpl); $j++) {
# ersetze die FileTemplates mit den echten MP3-Files
@FileTplPc = split(/:/, $FileTpl[$j]);
$text[$i] = $TTS_FileTemplateDir ."/". $FileTplPc[1] if($text[$i] eq $FileTplPc[0]);
}
Log3 $hash, 4, "$me: $i => ".$text[$i];
}
push( @{$hash->{helper}{Text2Speech}}, @text );
}
#####################################
# param1: array : Text 2 Speech
# param2: string: MaxChar
# param3: string: Delimiter
# param4: int : 1 -> es wird am Delimiter gesplittet
# 0 -> es wird nur gesplittet, wenn Stringlänge länger als MaxChar
# param5: string: Add Delimiter to String? [al|af|<empty>] (AddLast/AddFirst)
#
# Splittet die Texte aus $hash->{helper}->{Text2Speech} anhand des
# Delimiters, wenn die Stringlänge MaxChars übersteigt.
# Ist "AddDelimiter" angegeben, so wird der Delimiter an den
# String wieder angefügt
#####################################
sub Text2Speech_SplitString($$$$$){
my @text = @{shift()};
my $MaxChar = shift;
my $Delimiter = shift;
my $ForceSplit = shift;
my $AddDelimiter = shift;
my @newText;
for(my $i=0; $i<(@text); $i++) {
if((length($text[$i]) <= $MaxChar) && (!$ForceSplit)) { #Google kann nur 100zeichen
push(@newText, $text[$i]);
next;
}
my @b;
if($Delimiter =~/^ $/) {
@b = split(' ', $text[$i]);
}
else {
@b = split(/$Delimiter/, $text[$i]);
}
if((@b)>1) {
# setze zu kleine Textbausteine wieder zusammen bis MaxChar erreicht ist
if(length($Delimiter)==1) {
for(my $k=0; $k<(@b); ) {
if($k+1<(@b) && length($b[$k])+length($b[$k+1]) <= $MaxChar) {
$b[$k] = join($Delimiter, $b[$k], $b[$k+1]);
splice(@b, $k+1, 1);
}
else {
$k++;
}
}
}
for(my $j=0; $j<(@b); $j++) {
(my $boundaryDelimiter = $Delimiter) =~ s/^\\b(.+)\\b$/$1/g;
$b[$j] = $b[$j] . $boundaryDelimiter if($AddDelimiter eq "al"); # Am Satzende wieder hinzufügen.
$b[$j+1] = $boundaryDelimiter . $b[$j+1] if(($AddDelimiter eq "af") && ($b[$j+1])); # Am Satzanfang des nächsten Satzes wieder hinzufügen.
push(@newText, $b[$j]);
}
}
elsif((@b)==1) {
push(@newText, $text[$i]);
}
}
return @newText;
}
#####################################
# param1: hash : Hash
# param2: string: Datei
#
# Erstellt den Commandstring für den Systemaufruf
#####################################
sub Text2Speech_BuildMplayerCmdString($$) {
my ($hash, $file) = @_;
my $cmd;
my $TTS_MplayerCall = AttrVal($hash->{NAME}, "TTS_MplayerCall", $mplayer);
my $TTS_VolumeAdjust = AttrVal($hash->{NAME}, "TTS_VolumeAdjust", 110);
my $verbose = AttrVal($hash->{NAME}, "verbose", 3);
if($hash->{VOLUME}) { # per: set <name> volume <..>
$mplayerOpts .= " -softvol -softvol-max ". $TTS_VolumeAdjust ." -volume " . $hash->{VOLUME};
}
my $AlsaDevice = $hash->{ALSADEVICE};
if($AlsaDevice eq "default") {
$AlsaDevice = "";
$mplayerAudioOpts = "";
}
my $NoDebug = $mplayerNoDebug;
$NoDebug = "" if($verbose >= 5);
# anstatt mplayer wird ein anderer Player verwendet
if ($TTS_MplayerCall !~ m/mplayer/) {
$TTS_MplayerCall =~ s/{device}/$AlsaDevice/g;
$TTS_MplayerCall =~ s/{volume}/$hash->{VOLUME}/g;
$TTS_MplayerCall =~ s/{volumeadjust}/$TTS_VolumeAdjust/g;
$TTS_MplayerCall =~ s/{file}/$file/g;
$TTS_MplayerCall =~ s/{options}/$hash->{helper}{TTS_PlayerOptions}/g;
$cmd = $TTS_MplayerCall;
} else {
$cmd = $TTS_MplayerCall . " " . $mplayerAudioOpts . $AlsaDevice . " " .$NoDebug. " " . $mplayerOpts . " " . $file;
}
my $mp3Duration = Text2Speech_CalcMP3Duration($hash, $file);
BlockingInformParent("Text2Speech_readingsSingleUpdateByName", [$hash->{NAME}, "duration", "$mp3Duration"], 0);
BlockingInformParent("Text2Speech_readingsSingleUpdateByName", [$hash->{NAME}, "endTime", "00:00:00"], 0);
return $cmd;
}
#####################################
# Benutzt um Infos aus dem Blockingprozess
# in die Readings zu schreiben
#####################################
sub Text2Speech_readingsSingleUpdateByName($$$) {
my ($devName, $readingName, $readingVal) = @_;
my $hash = $defs{$devName};
Log3 $hash, 5, $hash->{NAME}.": readingsSingleUpdateByName: Dev:$devName Reading:$readingName Val:$readingVal";
readingsSingleUpdate($hash, $readingName, $readingVal, 1);
}
#####################################
# param1: string: MP3 Datei inkl. Pfad
#
# Ermittelt die Abspieldauer einer MP3 und gibt die Zeit in Sekunden zurück.
# Die Abspielzeit wird auf eine ganze Zahl gerundet
#####################################
sub Text2Speech_CalcMP3Duration($$) {
my $time;
my ($hash, $file) = @_;
eval {
my $tag = get_mp3info($file);
if ($tag && defined($tag->{SECS})) {
$time = int($tag->{SECS}+0.5);
Log3 $hash, 4, $hash->{NAME}.": $file hat eine Länge von $time Sekunden.";
}
};
if ($@) {
Log3 $hash, 2, $hash->{NAME}.": Bei der MP3-Längenermittlung ist ein Fehler aufgetreten: $@";
return undef;
}
return $time;
}
#####################################
# param1: hash : Hash
# param2: string: Dateiname
# param2: string: Text
#
# Holt den Text mithilfe der entsprechenden TTS_Ressource
#####################################
sub Text2Speech_Download($$$) {
my ($hash, $file, $text) = @_;
my $TTS_Ressource = AttrVal($hash->{NAME}, "TTS_Ressource", "Google");
my $TTS_User = AttrVal($hash->{NAME}, "TTS_User", "");
my $TTS_APIKey = AttrVal($hash->{NAME}, "TTS_APIKey", "");
my $TTS_Language = AttrVal($hash->{NAME}, "TTS_Language_Custom", $language{$TTS_Ressource}{AttrVal($hash->{NAME}, "TTS_Language", "Deutsch")});
my $TTS_Quality = AttrVal($hash->{NAME}, "TTS_Quality", "");
my $TTS_Speed = AttrVal($hash->{NAME}, "TTS_Speed", "");
my $cmd;
Log3 $hash->{NAME}, 4, $hash->{NAME}.": Verwende ".$TTS_Ressource." Resource zur TTS-Generierung";
if($TTS_Ressource =~ m/(Google|VoiceRSS)/) {
my $HttpResponse;
my $HttpResponseErr;
my $fh;
my $url = "https://" . $ttsHost{$TTS_Ressource} . $ttsPath{$TTS_Ressource};
$url .= $ttsLang{$TTS_Ressource} . $TTS_Language;
$url .= "&" . $ttsAddon{$TTS_Ressource} if(length($ttsAddon{$TTS_Ressource})>0);
$url .= "&" . $ttsUser{$TTS_Ressource} . $TTS_User if(length($ttsUser{$TTS_Ressource})>0);
$url .= "&" . $ttsAPIKey{$TTS_Ressource} . $TTS_APIKey if(length($ttsAPIKey{$TTS_Ressource})>0);
$url .= "&" . $ttsQuality{$TTS_Ressource} . $TTS_Quality if(length($ttsQuality{$TTS_Ressource})>0);
$url .= "&" . $ttsSpeed{$TTS_Ressource} . $TTS_Speed if(length($ttsSpeed{$TTS_Ressource})>0);
$url .= "&" . $ttsQuery{$TTS_Ressource} . uri_escape($text);
Log3 $hash->{NAME}, 4, $hash->{NAME}.": Hole URL: ". $url;
#$HttpResponse = GetHttpFile($ttsHost, $ttsPath . $ttsLang . $TTS_Language . "&" . $ttsQuery . uri_escape($text));
my $param = {
url => $url,
timeout => 5,
hash => $hash, # Muss gesetzt werden, damit die Callback funktion wieder $hash hat
method => "GET" # Lesen von Inhalten
#httpversion => "1.1",
#header => "User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22m" # Den Header gemäss abzufragender Daten ändern
#header => "agent: Mozilla/1.22\r\nUser-Agent: Mozilla/1.22"
};
($HttpResponseErr, $HttpResponse) = HttpUtils_BlockingGet($param);
if(length($HttpResponseErr) > 0) {
Log3 $hash->{NAME}, 3, $hash->{NAME}.": Fehler beim abrufen der Daten von " .$TTS_Ressource. " Translator";
Log3 $hash->{NAME}, 3, $hash->{NAME}.": " . $HttpResponseErr;
}
$fh = new IO::File ">$file";
if(!defined($fh)) {
Log3 $hash->{NAME}, 2, $hash->{NAME}.": mp3 Datei <$file> konnte nicht angelegt werden.";
return undef;
}
$fh->print($HttpResponse);
Log3 $hash->{NAME}, 4, $hash->{NAME}.": Schreibe mp3 in die Datei $file mit ".length($HttpResponse)." Bytes";
close($fh);
}
elsif ($TTS_Ressource eq "ESpeak") {
my $FileWav = $file . ".wav";
$cmd = "sudo espeak -vde+f3 -k5 -s150 \"" . $text . "\" -w \"" . $FileWav . "\"";
Log3 $hash, 4, $hash->{NAME}.":" .$cmd;
system($cmd);
$cmd = "lame \"" . $FileWav . "\" \"" . $file . "\"";
Log3 $hash, 4, $hash->{NAME}.":" .$cmd;
system($cmd);
unlink $FileWav;
}
elsif ($TTS_Ressource eq "SVOX-pico") {
my $FileWav = $file . ".wav";
$cmd = "pico2wave --lang=" . $TTS_Language . " --wave=\"" . $FileWav . "\" \"" . $text . "\"";
Log3 $hash, 4, $hash->{NAME}.":" .$cmd;
system($cmd);
$cmd = "lame \"" . $FileWav . "\" \"" . $file . "\"";
Log3 $hash, 4, $hash->{NAME}.":" .$cmd;
system($cmd);
unlink $FileWav;
}
elsif ($TTS_Ressource eq "Amazon-Polly") {
# with awscli
# aws polly synthesize-speech --output-format mp3 --voice-id Marlene --text '%text%' abc.mp3
#$cmd = "aws polly synthesize-speech --output-format json --speech-mark-types='[\"viseme\"]' --voice-id " . $TTS_Language . " --text '" . $text . "' " . $file;
#Log3 $hash, 4, $hash->{NAME}.":" .$cmd;
#system($cmd);
my $fh;
my $texttype = "text";
$texttype = "ssml" if($text =~ m/^<speak>.*<\/speak>$/);
Log3 $hash->{NAME}, 4, $hash->{NAME}.": Folgender TextTyp wurde für ".$TTS_Ressource." erkannt: ".$texttype;
my $polly = Paws->service('Polly', region => 'eu-central-1');
my $res = $polly->SynthesizeSpeech(
VoiceId => $TTS_Language,
Text => $text,
TextType => $texttype,
OutputFormat => 'mp3',
);
$fh = new IO::File ">$file";
if(!defined($fh)) {
Log3 $hash->{NAME}, 2, $hash->{NAME}.": mp3 Datei <$file> konnte nicht angelegt werden.";
return undef;
}
$fh->print($res->AudioStream);
Log3 $hash->{NAME}, 4, $hash->{NAME}.": Schreibe mp3 in die Datei $file mit ". $res->RequestCharacters ." Chars";
close($fh);
}
if ( $TTS_Ressource eq 'maryTTS' ) {
my $mTTSurl = $TTS_User;
my($unnamed, $named) = parseParams($mTTSurl);
$named->{host} //= shift @{$unnamed} // '127.0.0.1';
$named->{port} //= shift @{$unnamed} // '59125';
$named->{lang} //= shift @{$unnamed} // !$TTS_Language || $TTS_Language eq 'Deutsch' ? 'de_DE' : $TTS_Language;
$named->{voice} //= shift @{$unnamed} // 'de_DE/thorsten_low';
$named->{endpoint} //= shift @{$unnamed} // 'process';
$mTTSurl = "http://$named->{host}:$named->{port}/$named->{endpoint}?INPUT_TYPE=TEXT&OUTPUT_TYPE=AUDIO&AUDIO=WAVE_FILE&LOCALE=$named->{lang}&VOICE=$named->{voice}&INPUT_TEXT="; # https://github.com/marytts/marytts-txt2wav/blob/python/txt2wav.py#L21
$mTTSurl .= uri_escape($text);
Log3( $hash->{NAME}, 4, "$hash->{NAME}: Hole URL: $mTTSurl" );
my $param = { url => $mTTSurl,
timeout => 5,
hash => $hash, # Muss gesetzt werden, damit die Callback funktion wieder $hash hat
method => 'GET' # POST can be found in https://github.com/marytts/marytts-txt2wav/blob/python/txt2wav.py#L33
};
my ($maryTTSResponseErr, $maryTTSResponse) = HttpUtils_BlockingGet($param);
if(length($maryTTSResponseErr) > 0) {
Log3($hash->{NAME}, 3, "$hash->{NAME}: Fehler beim Abrufen der Daten von $TTS_Ressource: $maryTTSResponseErr");
return;
}
my $FileWav2 = $file . '.wav';
my $fh2 = new IO::File ">$FileWav2";
if ( !defined $FileWav2 ) {
Log3($hash->{NAME}, 2, "$hash->{NAME}: wav Datei <$FileWav2> konnte nicht angelegt werden.");
return;
}
$fh2->print($maryTTSResponse);
Log3($hash->{NAME}, 4, "$hash->{NAME}: Schreibe wav in die Datei $FileWav2 mit ".length $maryTTSResponse . ' Bytes');
close $fh2;
$cmd = qq(lame "$FileWav2" "$file");