-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvoicetools.py
1685 lines (1608 loc) · 66.2 KB
/
voicetools.py
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
__version__ = (1, 0, 35)
# ▄▀█ █▄ █ █▀█ █▄ █ █▀█ ▀▀█ █▀█ █ █ █▀
# █▀█ █ ▀█ █▄█ █ ▀█ ▀▀█ █ ▀▀█ ▀▀█ ▄█
#
# © Copyright 2024
#
# developed by @anon97945
#
# https://t.me/apodiktum_modules
# https://github.com/anon97945
#
# 🔒 Licensed under the GNU GPLv3
# 🌐 https://www.gnu.org/licenses/gpl-3.0.html
# meta developer: @apodiktum_modules
# meta banner: https://t.me/apodiktum_dumpster/11
# meta pic: https://t.me/apodiktum_dumpster/13
# scope: ffmpeg
# scope: hikka_only
# scope: hikka_min 1.3.3
# requires: numpy scipy noisereduce soundfile pyrubberband
import asyncio
import io
import logging
import os
import noisereduce as nr
import numpy as np
import pyrubberband
import scipy.io.wavfile as wavfile
import soundfile
from pydub import AudioSegment, effects
from telethon.tl.types import Message
from .. import loader, utils
logger = logging.getLogger(__name__)
async def getchattype(message: Message) -> str:
if message.is_group:
return "supergroup" if message.is_channel else "smallgroup"
if message.is_channel:
return "channel"
if message.is_private:
return "private"
def represents_nr(nr_lvl: str) -> bool:
try:
float(nr_lvl)
return 0.01 <= float(nr_lvl) <= 1
except ValueError:
return False
def represents_pitch(pitch_lvl: str) -> bool:
try:
float(pitch_lvl)
return -18 <= float(pitch_lvl) <= 18
except ValueError:
return False
def represents_speed(s: str) -> bool:
try:
float(s)
return 0.25 <= float(s) <= 3
except ValueError:
return False
def represents_gain(s: str) -> bool:
try:
float(s)
return -10 <= float(s) <= 10
except ValueError:
return False
async def audiohandler(
bytes_io_file: io.BytesIO,
filename: str,
file_ext: str,
new_file_ext: str,
channels: int,
codec: str,
) -> tuple:
bytes_io_file.seek(0)
bytes_io_file.name = filename + file_ext
out = filename + new_file_ext
if file_ext != new_file_ext:
new_fe_nodot = new_file_ext[1:]
with open(filename + file_ext, "wb") as f:
f.write(bytes_io_file.getbuffer())
bytes_io_file.seek(0)
sproc = await asyncio.create_subprocess_shell(
f"ffmpeg -y -i {filename + file_ext} -c:a {codec} -f {new_fe_nodot} -ar"
f" 48000 -b:a 320k -ac {channels} {out}",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
await sproc.communicate()
with open(out, "rb") as f:
bytes_io_file = io.BytesIO(f.read())
bytes_io_file.seek(0)
_, new_file_ext = os.path.splitext(out)
if os.path.exists(out):
os.remove(out)
if os.path.exists(filename + file_ext):
os.remove(filename + file_ext)
return bytes_io_file, filename, new_file_ext
async def audiopitcher(
bytes_io_file: io.BytesIO,
filename: str,
file_ext: str,
pitch_lvl: float,
) -> tuple:
bytes_io_file.seek(0)
bytes_io_file.name = filename + file_ext
format_ext = file_ext[1:]
y, sr = soundfile.read(bytes_io_file)
y_shift = pyrubberband.pitch_shift(y, sr, pitch_lvl)
bytes_io_file.seek(0)
soundfile.write(bytes_io_file, y_shift, sr, format=format_ext)
bytes_io_file.seek(0)
bytes_io_file.name = filename + file_ext
return bytes_io_file, filename, file_ext
async def audiodenoiser(
bytes_io_file: io.BytesIO,
filename: str,
file_ext: str,
nr_lvl: float,
) -> tuple:
bytes_io_file.seek(0)
bytes_io_file.name = filename + file_ext
rate, data = wavfile.read(bytes_io_file)
reduced_noise = nr.reduce_noise(
y=data,
sr=rate,
prop_decrease=nr_lvl,
stationary=False,
)
wavfile.write(bytes_io_file, rate, reduced_noise)
filename, file_ext = os.path.splitext(bytes_io_file.name)
return bytes_io_file, filename, file_ext
async def audionormalizer(
bytes_io_file: io.BytesIO,
filename: str,
file_ext: str,
gain: float,
) -> tuple:
bytes_io_file.seek(0)
bytes_io_file.name = filename + file_ext
format_ext = file_ext[1:]
rawsound = AudioSegment.from_file(bytes_io_file, format_ext)
normalizedsound = effects.normalize(rawsound)
normalizedsound = normalizedsound + gain
bytes_io_file.seek(0)
normalizedsound.export(bytes_io_file, format=format_ext)
bytes_io_file.name = filename + file_ext
filename, file_ext = os.path.splitext(bytes_io_file.name)
return bytes_io_file, filename, file_ext
async def audiospeedup(
bytes_io_file: io.BytesIO,
filename: str,
file_ext: str,
speed: float,
) -> tuple:
bytes_io_file.seek(0)
bytes_io_file.name = filename + file_ext
format_ext = file_ext[1:]
y, sr = soundfile.read(bytes_io_file)
y_stretch = pyrubberband.time_stretch(y, sr, speed)
bytes_io_file.seek(0)
soundfile.write(bytes_io_file, y_stretch, sr, format=format_ext)
bytes_io_file.seek(0)
bytes_io_file.name = filename + file_ext
return bytes_io_file, filename, file_ext
async def dalekvoice(bytes_io_file: io.BytesIO, filename: str, file_ext: str) -> tuple:
bytes_io_file.seek(0)
bytes_io_file.name = filename + file_ext
format_ext = file_ext[1:]
sound = AudioSegment.from_wav(bytes_io_file)
sound = sound.set_channels(2)
sound.export(bytes_io_file, format=format_ext)
bytes_io_file.seek(0)
VB = 0.2
VL = 0.4
H = 4
LOOKUP_SAMPLES = 1024
MOD_F = 50
def diode_lookup(n_samples: int) -> np.ndarray:
result = np.zeros((n_samples,))
for i in range(n_samples):
v = float(i - float(n_samples) / 2) / (n_samples / 2)
v = abs(v)
if v < VB:
result[i] = 0
elif VB < v <= VL:
result[i] = H * ((v - VB) ** 2) / (2 * VL - 2 * VB)
else:
result[i] = H * v - H * VL + (H * (VL - VB) ** 2) / (2 * VL - 2 * VB)
return result
rate, data = wavfile.read(bytes_io_file)
data = data[:, 1]
scaler = np.max(np.abs(data))
data = data.astype(np.float) / scaler
n_samples = data.shape[0]
d_lookup = diode_lookup(LOOKUP_SAMPLES)
diode = Waveshaper(d_lookup)
tone = np.arange(n_samples)
tone = np.sin(2 * np.pi * tone * MOD_F / rate)
tone = tone * 0.5
tone2 = tone.copy()
data2 = data.copy()
tone = -tone + data2
data = data + tone2
data = diode.transform(data) + diode.transform(-data)
tone = diode.transform(tone) + diode.transform(-tone)
result = data - tone
result /= np.max(np.abs(result))
result *= scaler
wavfile.write(bytes_io_file, rate, result.astype(np.int16))
bytes_io_file.name = filename + file_ext
filename, file_ext = os.path.splitext(bytes_io_file.name)
return bytes_io_file, filename, file_ext
class Waveshaper:
def __init__(self, curve):
self.curve = curve
self.n_bins = self.curve.shape[0]
def transform(self, samples: int) -> np.ndarray:
# normalize to 0 < samples < 2
max_val = np.max(np.abs(samples))
if max_val >= 1.0:
result = samples / np.max(np.abs(samples)) + 1.0
else:
result = samples + 1.0
result = result * (self.n_bins - 1) / 2
return self.curve[result.astype(np.int)]
@loader.tds
class ApodiktumVoiceToolsMod(loader.Module):
"""
Change, pitch, enhance your Voice. Also includes optional automatic modes.
"""
strings = {
"name": "Apo-VoiceTools",
"developer": "@anon97945",
"_cfg_gain_lvl": "Set the desired volume gain level for auto normalize.",
"_cfg_nr_lvl": "Set the desired noisereduction level.",
"_cfg_pitch_lvl": "Set the desired pitch level for auto pitch.",
"_cfg_speed_lvl": "Set the desired speed level for auto speed.",
"audiodenoiser_txt": "<b>[VoiceTools] Background noise is being removed.</b>",
"audiohandler_txt": "<b>[VoiceTools] Audio is being transcoded.</b>",
"audiovolume_txt": "<b>[VoiceTools] Audiovolume is being changed.</b>",
"auto_anon_off": "<b>❌ Anon Voice.</b>",
"auto_anon_on": "<b>✅ Anon Voice.</b>",
"auto_dalek_off": "<b>❌ Dalek Voice.</b>",
"auto_dalek_on": "<b>✅ Dalek Voice.</b>",
"auto_gain_off": "<b>❌ Volumegain.</b>",
"auto_gain_on": "<b>✅ Volumegain.</b>",
"auto_norm_off": "<b>❌ Normalize.</b>",
"auto_norm_on": "<b>✅ Normalize.</b>",
"auto_nr_off": "<b>❌ NoiseReduction.</b>",
"auto_nr_on": "<b>✅ NoiseReduction.</b>",
"auto_pitch_off": "<b>❌ Pitching.</b>",
"auto_pitch_on": "<b>✅ Pitching.</b>",
"auto_speed_off": "<b>❌ Speed.</b>",
"auto_speed_on": "<b>✅ Speed.</b>",
"current_auto": (
"<b>[VoiceTools]</b> Current AutoVoiceTools in this Chat are:\n\n{}"
),
"dalek_start": "<b>[VoiceTools]</b> Auto DalekVoice activated.",
"dalek_stopped": "<b>[VoiceTools]</b> Auto DalekVoice deactivated.",
"dalekvoice_txt": "<b>[VoiceTools] Dalek Voice is being applied.</b>",
"downloading": "<b>[VoiceTools] Message is being downloaded...</b>",
"error_file": "<b>[VoiceTools]</b> No file in the reply detected.",
"gain_start": "<b>[VoiceTools]</b> Auto VolumeGain activated.",
"gain_stopped": "<b>[VoiceTools]</b> Auto VolumeGain deactivated.",
"makewaves_txt": "<b>[VoiceTools] Speech waves are being applied.</b>",
"no_nr": (
"<b>[VoiceTools]</b> Your input was an unsupported noise reduction level."
),
"no_pitch": "<b>[VoiceTools]</b> Your input was an unsupported pitch level.",
"no_speed": "<b>[VoiceTools]</b> Your input was an unsupported speed level.",
"norm_start": "<b>[VoiceTools]</b> Auto VoiceNormalizer activated.",
"norm_stopped": "<b>[VoiceTools]</b> Auto VoiceNormalizer deactivated.",
"nr_level": "<b>[VoiceTools]</b> Noise reduction level set to {}.",
"nr_start": "<b>[VoiceTools]</b> Auto VoiceEnhancer activated.",
"nr_stopped": "<b>[VoiceTools]</b> Auto VoiceEnhancer deactivated.",
"pitch_level": "<b>[VoiceTools]</b> Pitch level set to {}.",
"pitch_start": "<b>[VoiceTools]</b> Auto VoicePitch activated.",
"pitch_stopped": "<b>[VoiceTools]</b> Auto VoicePitch deactivated.",
"pitch_txt": "<b>[VoiceTools] Pitch is being applied.</b>",
"speed_start": "<b>[VoiceTools]</b> Auto VoiceSpeed activated.",
"speed_stopped": "<b>[VoiceTools]</b> Auto VoiceSpeed deactivated.",
"speed_txt": "<b>[VoiceTools] Speed is being applied.</b>",
"uploading": "<b>[VoiceTools] File is uploading.</b>",
"vcanon_start": "<b>[VoiceTools]</b> Auto AnonVoice activated.",
"vcanon_stopped": "<b>[VoiceTools]</b> Auto AnonVoice deactivated.",
"vtauto_stopped": "<b>[VoiceTools]</b> Auto Voice Tools deactivated.",
"_cfg_cst_auto_migrate": "Wheather to auto migrate defined changes on startup.",
}
strings_en = {}
strings_de = {
"_cfg_gain_lvl": (
"Stellen Sie den gewünschten Lautstärkepegel für die automatische"
" Normalisierung ein."
),
"_cfg_nr_lvl": "Stellen Sie den gewünschten Rauschunterdrückungspegel ein.",
"_cfg_pitch_lvl": (
"Stellen Sie den gewünschten Tonhöhenpegel für die automatische"
" Tonhöheneinstellung ein."
),
"_cfg_speed_lvl": (
"Stellen Sie die gewünschte Geschwindigkeitsstufe für die"
" automatische Geschwindigkeit ein."
),
"_cmd_doc_cvoicetoolscmd": (
"Dadurch wird die Konfiguration für das Modul geöffnet."
),
"audiodenoiser_txt": (
"<b>[VoiceTools] Die Hintergrundgeräusche werden entfernt.</b>"
),
"audiohandler_txt": "<b>[VoiceTools] Der Ton wird transkodiert.</b>",
"audiovolume_txt": "<b>[VoiceTools] Das Audiovolumen wird angepasst.</b>",
"auto_anon_off": "<b>❌ Anon Voice.</b>",
"auto_anon_on": "<b>✅ Anon Voice.</b>",
"auto_dalek_off": "<b>❌ Dalek Voice.</b>",
"auto_dalek_on": "<b>✅ Dalek Voice.</b>",
"auto_gain_off": "<b>❌ Volumegain.</b>",
"auto_gain_on": "<b>✅ Volumegain.</b>",
"auto_norm_off": "<b>❌ Normalize.</b>",
"auto_norm_on": "<b>✅ Normalize.</b>",
"auto_nr_off": "<b>❌ NoiseReduction.</b>",
"auto_nr_on": "<b>✅ NoiseReduction.</b>",
"auto_pitch_off": "<b>❌ Pitching.</b>",
"auto_pitch_on": "<b>✅ Pitching.</b>",
"auto_speed_off": "<b>❌ Speed.</b>",
"auto_speed_on": "<b>✅ Speed.</b>",
"current_auto": (
"<b>[VoiceTools]</b> Aktuelle AutoVoiceTools in diesem Chat sind:\n\n{}"
),
"dalek_start": "<b>[VoiceTools]</b> Auto DalekVoice aktiviert.",
"dalek_stopped": "<b>[VoiceTools]</b> Auto DalekVoice ist deaktiviert.",
"dalekvoice_txt": "<b>[VoiceTools] Die Dalek-Stimme wird angewendet.</b>",
"downloading": "<b>[VoiceTools] Die Nachricht wird heruntergeladen...</b>",
"error_file": "<b>[VoiceTools]</b> Keine Datei in der Antwort gefunden.",
"gain_start": "<b>[VoiceTools]</b> Auto VolumeGain aktiviert.",
"gain_stopped": "<b>[VoiceTools]</b> Auto VolumeGain deaktiviert.",
"makewaves_txt": "<b>[VoiceTools] Es werden Sprachwellen erstellt.</b>",
"no_nr": (
"<b>[VoiceTools]</b> Ihre Eingabe war ein nicht unterstützter"
" Rauschunterdrückungspegel."
),
"no_pitch": (
"<b>[VoiceTools]</b> Ihre Eingabe war ein nicht unterstützter"
" Tonhöhenpegel."
),
"no_speed": (
"<b>[VoiceTools]</b> Ihre Eingabe war eine nicht unterstützte"
" Geschwindigkeitswert."
),
"norm_start": "<b>[VoiceTools]</b> Auto VoiceNormalizer aktiviert.",
"norm_stopped": "<b>[VoiceTools]</b> Auto VoiceNormalizer deaktiviert.",
"nr_level": "<b>[VoiceTools]</b> Rauschunterdrückungspegel auf {} eingestellt.",
"nr_start": "<b>[VoiceTools]</b> Auto VoiceEnhancer aktiviert.",
"nr_stopped": "<b>[VoiceTools]</b> Auto VoiceEnhancer deaktiviert.",
"pitch_level": "<b>[VoiceTools]</b> Die Tonhöhe ist auf {} eingestellt.",
"pitch_start": "<b>[VoiceTools]</b> Auto VoicePitch aktiviert.",
"pitch_stopped": "<b>[VoiceTools]</b> Auto VoicePitch deaktiviert.",
"pitch_txt": "<b>[VoiceTools] Pitch wird angewandt.</b>",
"speed_start": "<b>[VoiceTools]</b> Auto VoiceSpeed aktiviert.",
"speed_stopped": "<b>[VoiceTools]</b> Auto VoiceSpeed deaktiviert.",
"speed_txt": "<b>[VoiceTools] Geschwindigkeit wird angewendet.</b>",
"uploading": "<b>[VoiceTools] Datei wird hochgeladen.</b>",
"vcanon_start": "<b>[VoiceTools]</b> Auto AnonVoice aktiviert.",
"vcanon_stopped": "<b>[VoiceTools]</b> Auto AnonVoice deaktiviert.",
"vtauto_stopped": "<b>[VoiceTools]</b> Auto Voice Tools deaktiviert.",
}
strings_ru = {
"_cfg_gain_lvl": (
"Установите желаемый уровень усиления громкости для автоматического"
" питча. (Высоты тона)"
),
"_cfg_nr_lvl": "Установите желаемый уровень шумоподавления.",
"_cfg_pitch_lvl": "Установите желаемый уровень высоты тона для автонастройки.",
"_cfg_speed_lvl": (
"Установите желаемый уровень скорости для автоматической скорости."
),
"_cmd_doc_cvoicetoolscmd": "Это откроет конфиг для модуля.",
"audiodenoiser_txt": "<b>[VoiceTools] Фоновый шум удаляется.</b>",
"audiohandler_txt": "<b>[VoiceTools] Аудио перекодируется.</b>",
"audiovolume_txt": "<b>[VoiceTools] Аудиогромкость изменяется.</b>",
"auto_anon_off": "<b>❌ Anon Voice.</b>",
"auto_anon_on": "<b>✅ Anon Voice.</b>",
"auto_dalek_off": "<b>❌ Dalek Voice.</b>",
"auto_dalek_on": "<b>✅ Dalek Voice.</b>",
"auto_gain_off": "<b>❌ Volumegain.</b>",
"auto_gain_on": "<b>✅ Volumegain.</b>",
"auto_norm_off": "<b>❌ Normalize.</b>",
"auto_norm_on": "<b>✅ Normalize.</b>",
"auto_nr_off": "<b>❌ NoiseReduction.</b>",
"auto_nr_on": "<b>✅ NoiseReduction.</b>",
"auto_pitch_off": "<b>❌ Pitching.</b>",
"auto_pitch_on": "<b>✅ Pitching.</b>",
"auto_speed_off": "<b>❌ Speed.</b>",
"auto_speed_on": "<b>✅ Speed.</b>",
"current_auto": (
"<b>[VoiceTools]</b> Текущие авто-инструменты для работы с голосом"
" в этом чате:\n\n{}"
),
"dalek_start": "<b>[VoiceTools]</b> Активирован автоматический голос «Далека».",
"dalek_stopped": (
"<b>[VoiceTools]</b> Деактивирован автоматический голос «Далека»."
),
"dalekvoice_txt": "<b>[VoiceTools] Голос «Далека» применяется.</b>",
"downloading": "<b>[VoiceTools] Сообщение загружается...</b>",
"error_file": "<b>[VoiceTools]</b> Не обнаружен файл в реплае.",
"gain_start": (
"<b>[VoiceTools]</b> Активировано автоматическое усиление громкости."
),
"gain_stopped": (
"<b>[VoiceTools]</b> Деактивировано автоматическое усиление громкости."
),
"makewaves_txt": "<b>[VoiceTools] Речевые волны применяются.</b>",
"no_nr": (
"<b>[VoiceTools]</b> Введенное значение не является поддерживаемым уровнем"
" шумоподавления."
),
"no_pitch": (
"<b>[VoiceTools]</b> Введенное значение не является поддерживаемым уровнем"
" высоты тона."
),
"no_speed": (
"<b>[VoiceTools]</b> Введенное значение не является поддерживаемым уровнем"
" скорости звука."
),
"norm_start": "<b>[VoiceTools]</b> Активирована автонормализация голоса.",
"norm_stopped": "<b>[VoiceTools]</b> Деактивирована автонормализация голоса.",
"nr_level": "<b>[VoiceTools]</b> Уровень шумоподавления установлен на {}.",
"nr_start": "<b>[VoiceTools]</b> Активировано автоматическое усиление голоса.",
"nr_stopped": (
"<b>[VoiceTools]</b> Деактивировано автоматическое усиление голоса."
),
"pitch_level": "<b>[VoiceTools]</b> Уровень высоты тона установлен на {}.",
"pitch_start": "<b>[VoiceTools]</b> Активирован авто-питч. (Высота тона)",
"pitch_stopped": "<b>[VoiceTools]</b> Деактивирован авто-питч. (Высота тона)",
"pitch_txt": "<b>[VoiceTools] Высота тона применяется.</b>",
"speed_start": "<b>[VoiceTools]</b> Активировано автоускорение голоса.",
"speed_stopped": "<b>[VoiceTools]</b> Деактивировано автоускорение голоса.",
"speed_txt": "<b>[VoiceTools] Скорость применяется.</b>",
"uploading": "<b>[VoiceTools] Файл загружается.</b>",
"vcanon_start": (
"<b>[VoiceTools]</b> Активирован автоматический «анонимный голос»"
),
"vcanon_stopped": (
"<b>[VoiceTools]</b> Деактивирован автоматический «анонимный голос»"
),
"vtauto_stopped": (
"<b>[VoiceTools]</b> Деактивированы все автоматические инструменты"
" для работы с голосом."
),
}
all_strings = {
"strings": strings,
"strings_en": strings,
"strings_de": strings_de,
"strings_ru": strings_ru,
}
changes = {
"migration1": {
"name": {
"old": "Apo Voicetools",
"new": "Apo-Voicetools",
},
},
}
def __init__(self):
self._ratelimit = []
self.config = loader.ModuleConfig(
loader.ConfigValue(
"pitch_lvl",
"4",
doc=lambda: self.strings("_cfg_pitch_lvl"),
validator=loader.validators.Float(minimum=-18, maximum=18),
),
loader.ConfigValue(
"nr_lvl",
"0.85",
doc=lambda: self.strings("_cfg_nr_lvl"),
validator=loader.validators.Float(minimum=0.01, maximum=1),
),
loader.ConfigValue(
"gain_lvl",
"1.5",
doc=lambda: self.strings("_cfg_gain_lvl"),
validator=loader.validators.Float(minimum=-10, maximum=10),
),
loader.ConfigValue(
"speed_lvl",
"1",
doc=lambda: self.strings("_cfg_speed_lvl"),
validator=loader.validators.Float(minimum=0.25, maximum=3),
),
loader.ConfigValue(
"auto_migrate",
True,
doc=lambda: self.strings("_cfg_cst_auto_migrate"),
validator=loader.validators.Boolean(),
), # for MigratorClass
)
async def client_ready(self):
self._classname = self.__class__.__name__
self.apo_lib = await self.import_lib(
"https://raw.githubusercontent.com/anon97945/hikka-libs/master/apodiktum_library.py",
suspend_on_error=True,
)
await self.apo_lib.migrator.auto_migrate_handler(
self.__class__.__name__,
self.strings("name"),
self.changes,
self.config["auto_migrate"],
)
async def cvoicetoolscmd(self, message: Message):
"""
This will open the config for the module.
"""
name = self.strings("name")
await self.allmodules.commands["config"](
await utils.answer(message, f"{self.get_prefix()}config {name}")
)
async def vtdalekcmd(self, message):
"""reply to a file to change the voice"""
chatid = utils.get_chat_id(message)
SendAsVoice = False
if not message.is_reply:
return
replymsg = await message.get_reply_message()
SendAsVoice = bool(replymsg.voice)
if not replymsg.media:
return await utils.answer(
message,
self.apo_lib.utils.get_str("error_file", self.all_strings, message),
)
filename = replymsg.file.name or "voice"
ext = replymsg.file.ext
if ext == ".oga":
filename_new = filename.replace(ext, "")
filename_new = filename.replace(".ogg", "")
else:
filename_new = filename.replace(ext, "")
gain_lvl = 0
nr_lvl = self.config["nr_lvl"]
file = io.BytesIO()
file.name = replymsg.file.name
inline_msg = await self.inline.form(
message=message,
text=self.apo_lib.utils.get_str("downloading", self.all_strings, message),
reply_markup={"text": "\u0020\u2800", "callback": "empty"},
)
await self._client.download_file(replymsg, file)
file.name = filename_new + ext
filename, file_ext = os.path.splitext(file.name)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("audiohandler_txt", self.all_strings, message),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".wav", "1", "pcm_s16le"
)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("audiodenoiser_txt", self.all_strings, message),
)
file, filename, file_ext = await audiodenoiser(file, filename, file_ext, nr_lvl)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("audiovolume_txt", self.all_strings, message),
)
file, filename, file_ext = await audionormalizer(
file, filename, file_ext, gain_lvl
)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("dalekvoice_txt", self.all_strings, message),
)
file, filename, file_ext = await dalekvoice(file, filename, file_ext)
file.seek(0)
if SendAsVoice:
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("makewaves_txt", self.all_strings, message),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".ogg", "2", "libopus"
)
else:
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str(
"audiohandler_txt", self.all_strings, message
),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ext, "1", "libmp3lame"
)
file.seek(0)
file.name = filename + file_ext
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("uploading", self.all_strings, message),
)
await self._client.send_file(chatid, file, voice_note=SendAsVoice)
await inline_msg.delete()
async def vtanoncmd(self, message):
"""reply to a file to change the voice into anonymous"""
chatid = utils.get_chat_id(message)
SendAsVoice = False
if not message.is_reply:
return
replymsg = await message.get_reply_message()
SendAsVoice = bool(replymsg.voice)
if not replymsg.media:
return await utils.answer(
message,
self.apo_lib.utils.get_str("error_file", self.all_strings, message),
)
filename = replymsg.file.name or "voice"
ext = replymsg.file.ext
if ext == ".oga":
filename_new = filename.replace(ext, "")
filename_new = filename.replace(".ogg", "")
else:
filename_new = filename.replace(ext, "")
gain_lvl = 0
file = io.BytesIO()
file.name = replymsg.file.name
nr_lvl = 0.8
pitch_lvl = -4.5
inline_msg = await self.inline.form(
message=message,
text=self.apo_lib.utils.get_str("downloading", self.all_strings, message),
reply_markup={"text": "\u0020\u2800", "callback": "empty"},
)
await self._client.download_file(replymsg, file)
file.name = filename_new + ext
filename, file_ext = os.path.splitext(file.name)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("audiohandler_txt", self.all_strings, message),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".wav", "1", "pcm_s16le"
)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("audiodenoiser_txt", self.all_strings, message),
)
file, filename, file_ext = await audiodenoiser(file, filename, file_ext, nr_lvl)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("audiovolume_txt", self.all_strings, message),
)
file, filename, file_ext = await audionormalizer(
file, filename, file_ext, gain_lvl
)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("dalekvoice_txt", self.all_strings, message),
)
file, filename, file_ext = await dalekvoice(file, filename, file_ext)
file.seek(0)
file, filename, file_ext = await audiopitcher(
file, filename, file_ext, pitch_lvl
)
file.seek(0)
if SendAsVoice:
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("makewaves_txt", self.all_strings, message),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".ogg", "2", "libopus"
)
else:
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str(
"audiohandler_txt", self.all_strings, message
),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ext, "1", "libmp3lame"
)
file.seek(0)
file.name = filename + file_ext
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("uploading", self.all_strings, message),
)
await self._client.send_file(chatid, file, voice_note=SendAsVoice)
await inline_msg.delete()
async def vtpitchcmd(self, message):
"""reply to a file to pitch voice
- Example: .vtpitch 12
Possible values between -18 and 18"""
chatid = utils.get_chat_id(message)
SendAsVoice = False
if not message.is_reply:
return
replymsg = await message.get_reply_message()
SendAsVoice = bool(replymsg.voice)
if not replymsg.media:
return await utils.answer(
message,
self.apo_lib.utils.get_str("error_file", self.all_strings, message),
)
pitch_lvl = utils.get_args_raw(message)
if not represents_pitch(pitch_lvl):
return await utils.answer(
message,
self.apo_lib.utils.get_str("no_pitch", self.all_strings, message),
)
filename = replymsg.file.name or "voice"
ext = replymsg.file.ext
if ext == ".oga":
filename_new = filename.replace(ext, "")
filename_new = filename.replace(".ogg", "")
else:
filename_new = filename.replace(ext, "")
gain_lvl = 0
file = io.BytesIO()
file.name = replymsg.file.name
inline_msg = await self.inline.form(
message=message,
text=self.apo_lib.utils.get_str("downloading", self.all_strings, message),
reply_markup={"text": "\u0020\u2800", "callback": "empty"},
)
await self._client.download_file(replymsg, file)
file.name = filename_new + ext
filename, file_ext = os.path.splitext(file.name)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("audiohandler_txt", self.all_strings, message),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".mp3", "1", "libmp3lame"
)
file.seek(0)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".flac", "1", "flac"
)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("pitch_txt", self.all_strings, message),
)
file, filename, file_ext = await audiopitcher(
file, filename, file_ext, float(pitch_lvl)
)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("audiovolume_txt", self.all_strings, message),
)
file, filename, file_ext = await audionormalizer(
file, filename, file_ext, gain_lvl
)
file.seek(0)
if SendAsVoice:
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("makewaves_txt", self.all_strings, message),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".ogg", "2", "libopus"
)
else:
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str(
"audiohandler_txt", self.all_strings, message
),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ext, "1", "libmp3lame"
)
file.seek(0)
file.name = filename + file_ext
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("uploading", self.all_strings, message),
)
await self._client.send_file(chatid, file, voice_note=SendAsVoice)
await inline_msg.delete()
async def vtspeedcmd(self, message):
"""reply to a file to increase speed and reduce length
- Example: .vtspeed 1.5
Possible values between 0.25 - 3"""
chatid = utils.get_chat_id(message)
SendAsVoice = False
if not message.is_reply:
return
replymsg = await message.get_reply_message()
SendAsVoice = bool(replymsg.voice)
if not replymsg.media:
return await utils.answer(
message,
self.apo_lib.utils.get_str("error_file", self.all_strings, message),
)
speed_lvl = utils.get_args_raw(message)
if not represents_speed(speed_lvl):
return await utils.answer(
message,
self.apo_lib.utils.get_str("no_speed", self.all_strings, message),
)
filename = replymsg.file.name or "voice"
ext = replymsg.file.ext
if ext == ".oga":
filename_new = filename.replace(ext, "")
filename_new = filename.replace(".ogg", "")
else:
filename_new = filename.replace(ext, "")
gain_lvl = 0
file = io.BytesIO()
file.name = replymsg.file.name
inline_msg = await self.inline.form(
message=message,
text=self.apo_lib.utils.get_str("downloading", self.all_strings, message),
reply_markup={"text": "\u0020\u2800", "callback": "empty"},
)
await self._client.download_file(replymsg, file)
file.name = filename_new + ext
filename, file_ext = os.path.splitext(file.name)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("audiohandler_txt", self.all_strings, message),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".mp3", "1", "libmp3lame"
)
file.seek(0)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".flac", "1", "flac"
)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("speed_txt", self.all_strings, message),
)
file, filename, file_ext = await audiospeedup(
file, filename, file_ext, float(speed_lvl)
)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("audiovolume_txt", self.all_strings, message),
)
file, filename, file_ext = await audionormalizer(
file, filename, file_ext, gain_lvl
)
file.seek(0)
if SendAsVoice:
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("makewaves_txt", self.all_strings, message),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".ogg", "2", "libopus"
)
else:
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str(
"audiohandler_txt", self.all_strings, message
),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ext, "1", "libmp3lame"
)
file.seek(0)
file.name = filename + file_ext
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("uploading", self.all_strings, message),
)
await self._client.send_file(chatid, file, voice_note=SendAsVoice)
await inline_msg.delete()
async def vtgaincmd(self, message):
"""reply to a file to change the volume
- Example: .vtgain 1
Possible values between -10 - 10"""
chatid = utils.get_chat_id(message)
SendAsVoice = False
if not message.is_reply:
return
replymsg = await message.get_reply_message()
SendAsVoice = bool(replymsg.voice)
if not replymsg.media:
return await utils.answer(
message,
self.apo_lib.utils.get_str("error_file", self.all_strings, message),
)
gain_lvl = utils.get_args_raw(message)
if not represents_gain(gain_lvl):
return await utils.answer(
message,
self.apo_lib.utils.get_str("no_speed", self.all_strings, message),
)
filename = replymsg.file.name or "voice"
ext = replymsg.file.ext
if ext == ".oga":
filename_new = filename.replace(ext, "")
filename_new = filename.replace(".ogg", "")
else:
filename_new = filename.replace(ext, "")
file = io.BytesIO()
file.name = replymsg.file.name
inline_msg = await self.inline.form(
message=message,
text=self.apo_lib.utils.get_str("downloading", self.all_strings, message),
reply_markup={"text": "\u0020\u2800", "callback": "empty"},
)
await self._client.download_file(replymsg, file)
file.name = filename_new + ext
filename, file_ext = os.path.splitext(file.name)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,
self.apo_lib.utils.get_str("audiohandler_txt", self.all_strings, message),
)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".mp3", "1", "libmp3lame"
)
file.seek(0)
file, filename, file_ext = await audiohandler(
file, filename, file_ext, ".flac", "1", "flac"
)
file.seek(0)
inline_msg = await utils.answer(
inline_msg,